Rectangle 27 109

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.

+1 for mentioning JSON with example.

You have quotes round <?php echo $simple; ?> and I think that's right. But you have quotes round <?php echo json_encode($complex); ?> as well, and I think that's wrong --- json_encode() returns valid javascript, so you don't want to quote it, surely?

Interaction between Javascript and PHP on the same PHP file, not on different PHP files.

aha, but it cannot be called in js files with .js extensions(

How to access PHP variables in JavaScript or jQuery rather than php javascript jquery

Rectangle 27 108

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.

+1 for mentioning JSON with example.

You have quotes round <?php echo $simple; ?> and I think that's right. But you have quotes round <?php echo json_encode($complex); ?> as well, and I think that's wrong --- json_encode() returns valid javascript, so you don't want to quote it, surely?

Interaction between Javascript and PHP on the same PHP file, not on different PHP files.

aha, but it cannot be called in js files with .js extensions(

How to access PHP variables in JavaScript or jQuery rather than php javascript jquery

Rectangle 27 4

It depends on how deep you want the serialization to work. You can use the $.param(obj) method in jQuery to do simple object serialization, but it won't work on your example as it assumes that the values are simple types or arrays of simple types. You might want to look at the code for param and adapt it to your specialized needs. Essentially, you'd need to determine when the value is an object and use that to append the keys in the object to the outer key when constructing the key/value arrays. Handling arrays of complex objects would take some similar fiddling to get the key indices set up correctly.

The following has been tested in FF3.5/IE8. No guarantees for other browsers but I think it ought to work.

jQuery.extend( {
    isObject: function(obj) {
       return typeof(obj) === "object";
    },
    complexParam: function( a ) {
        var s = [ ];

        function add( key, value ){
            s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
        };

        // If an array was passed in, assume that it is an array
        // of form elements
        if ( jQuery.isArray(a) || a.jquery )
            // Serialize the form elements
            jQuery.each( a, function(){
                add( this.name, this.value );
            });

        // Otherwise, assume that it's an object of key/value pairs
        else
            // Serialize the key/values
            for ( var j in a )
                // If the value is an array then the key names need to be repeated
                if ( jQuery.isArray(a[j]) )
                    jQuery.each( a[j], function(){
                        if (jQuery.isObject(this)) {
                            var idx = 0;
                            for (var k in this) {
                               add( j + "[" + idx + "]." + k, this[k] );
                               ++idx;
                            }
                        }
                        else {
                             add( j, this );
                        }
                    });
                else {
                    if (jQuery.isFunction(a[j])) {
                       add( j, a[j]() );
                    }
                    else if (jQuery.isObject(a[j])) {
                       for (var k in a[j]) {
                          add( j + "." + k, a[j][k] );
                       }
                    }
                    else {
                        add( j, a[j] );
                    }
                }

        // Return the resulting serialization
        return s.join("&").replace(/%20/g, "+");
    }
});

Called as

var serialized = $.complexParam( obj );

Note that this leaves the brackets URL-encoded. If that isn't ok, then add

.replace(/%5B/g, "[").replace(/%5D/g, "]")

to the return in complexParam()

Thanks! Finally someone who read the question :) I just adapted your code to use Mootools instead. I'll post that shortly.

Simulating a form POST to ASP.NET MVC with javascript - Stack Overflow

javascript asp.net-mvc json
Rectangle 27 4

It depends on how deep you want the serialization to work. You can use the $.param(obj) method in jQuery to do simple object serialization, but it won't work on your example as it assumes that the values are simple types or arrays of simple types. You might want to look at the code for param and adapt it to your specialized needs. Essentially, you'd need to determine when the value is an object and use that to append the keys in the object to the outer key when constructing the key/value arrays. Handling arrays of complex objects would take some similar fiddling to get the key indices set up correctly.

The following has been tested in FF3.5/IE8. No guarantees for other browsers but I think it ought to work.

jQuery.extend( {
    isObject: function(obj) {
       return typeof(obj) === "object";
    },
    complexParam: function( a ) {
        var s = [ ];

        function add( key, value ){
            s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
        };

        // If an array was passed in, assume that it is an array
        // of form elements
        if ( jQuery.isArray(a) || a.jquery )
            // Serialize the form elements
            jQuery.each( a, function(){
                add( this.name, this.value );
            });

        // Otherwise, assume that it's an object of key/value pairs
        else
            // Serialize the key/values
            for ( var j in a )
                // If the value is an array then the key names need to be repeated
                if ( jQuery.isArray(a[j]) )
                    jQuery.each( a[j], function(){
                        if (jQuery.isObject(this)) {
                            var idx = 0;
                            for (var k in this) {
                               add( j + "[" + idx + "]." + k, this[k] );
                               ++idx;
                            }
                        }
                        else {
                             add( j, this );
                        }
                    });
                else {
                    if (jQuery.isFunction(a[j])) {
                       add( j, a[j]() );
                    }
                    else if (jQuery.isObject(a[j])) {
                       for (var k in a[j]) {
                          add( j + "." + k, a[j][k] );
                       }
                    }
                    else {
                        add( j, a[j] );
                    }
                }

        // Return the resulting serialization
        return s.join("&").replace(/%20/g, "+");
    }
});

Called as

var serialized = $.complexParam( obj );

Note that this leaves the brackets URL-encoded. If that isn't ok, then add

.replace(/%5B/g, "[").replace(/%5D/g, "]")

to the return in complexParam()

Thanks! Finally someone who read the question :) I just adapted your code to use Mootools instead. I'll post that shortly.

Simulating a form POST to ASP.NET MVC with javascript - Stack Overflow

javascript asp.net-mvc json
Rectangle 27 1

You need to make sure your web server (e.g. Apache or Nginx) accepts requests to that URL and redirects it properly. There are many ways to do this. For example, your web server could redirect all or most requests to a central PHP file that routes the request further. This is generally preferably in more complex systems. However, for simpler cases it might be enough to use something like mod_rewrite (if you're using Apache as your web server).

Assuming your setup allows it, putting something like the following in a .htaccess file in your document root would cause mod_rewrite to forward all requests to www.mydomain.com/profile to www.mydomain.com/profile.php:

RewriteEngine  on
RewriteRule    "^/profile$"  "profile.php"  [L]

That's a very simple example that'll only work for that specific page, but if you have a lot of pages that follow the same naming standard you can apply more generalised rules as well.

If you're using something other than Apache to serve your pages, there are similar features in virtually all of them.

that's won't work since the site has many pages, so it should be dynamic, if I have to specify each url location it will take forever. Thank you.

@AhmadzIssa As mentioned, mod_rewrite and similar solutions allow for more general solutions that do not require a separate rule for each URL. If you want to know exactly how, you'd need to provide a fairly detailed specification of what you want to be rewritten into what. I'd suggest reading the documentation for mod_rewrite.

javascript - (Ajax) land on page url without reloading the content - S...

javascript php jquery ajax
Rectangle 27 96

If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.

It was written by a co-founder of Github. Example Flash embed code below:

<object 
   classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   width="110"
   height="14"
   id="clippy">
  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>
  <embed 
     src="/flash/clippy.swf"
     width="110"
     height="14"
     name="clippy"
     quality="high"
     allowScriptAccess="always"
     type="application/x-shockwave-flash"
     pluginspage="http://www.macromedia.com/go/getflashplayer"
     FlashVars="text=#{text}"
     bgcolor="#{bgcolor}"/>
</object>

Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.

For anyone interested, check Clippy being used on GitHub when copying the URL for the repo.

Excuseme, where is the rest of the code? what are the methods that can be used? how is this integrted? the actual download do not include examples nor anwsers to the questions I am doing here. Thanks a lot

FYI, use of Clippy on GitHub has been replaced by ZeroClipboard.

The OP wanted a solution in JavaScript. Not flash.

@MT, by "javascript" some people mean "in the browser client", so while JS-only might be a requirement, many of the people who chance upon this answer are really looking for JS-or-other-widely-supported-client-tech. Flash doesn't hit all platforms, but for a polish feature like clipboard support, it is worth adding if it improves the UX over a popup dialog (which it certainly does).

How do I copy to the clipboard in JavaScript? - Stack Overflow

javascript clipboard copy-paste
Rectangle 27 96

If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.

It was written by a co-founder of Github. Example Flash embed code below:

<object 
   classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   width="110"
   height="14"
   id="clippy">
  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>
  <embed 
     src="/flash/clippy.swf"
     width="110"
     height="14"
     name="clippy"
     quality="high"
     allowScriptAccess="always"
     type="application/x-shockwave-flash"
     pluginspage="http://www.macromedia.com/go/getflashplayer"
     FlashVars="text=#{text}"
     bgcolor="#{bgcolor}"/>
</object>

Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.

For anyone interested, check Clippy being used on GitHub when copying the URL for the repo.

Excuseme, where is the rest of the code? what are the methods that can be used? how is this integrted? the actual download do not include examples nor anwsers to the questions I am doing here. Thanks a lot

FYI, use of Clippy on GitHub has been replaced by ZeroClipboard.

The OP wanted a solution in JavaScript. Not flash.

@MT, by "javascript" some people mean "in the browser client", so while JS-only might be a requirement, many of the people who chance upon this answer are really looking for JS-or-other-widely-supported-client-tech. Flash doesn't hit all platforms, but for a polish feature like clipboard support, it is worth adding if it improves the UX over a popup dialog (which it certainly does).

How do I copy to the clipboard in JavaScript? - Stack Overflow

javascript clipboard copy-paste
Rectangle 27 96

If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.

It was written by a co-founder of Github. Example Flash embed code below:

<object 
   classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   width="110"
   height="14"
   id="clippy">
  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>
  <embed 
     src="/flash/clippy.swf"
     width="110"
     height="14"
     name="clippy"
     quality="high"
     allowScriptAccess="always"
     type="application/x-shockwave-flash"
     pluginspage="http://www.macromedia.com/go/getflashplayer"
     FlashVars="text=#{text}"
     bgcolor="#{bgcolor}"/>
</object>

Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.

For anyone interested, check Clippy being used on GitHub when copying the URL for the repo.

Excuseme, where is the rest of the code? what are the methods that can be used? how is this integrted? the actual download do not include examples nor anwsers to the questions I am doing here. Thanks a lot

FYI, use of Clippy on GitHub has been replaced by ZeroClipboard.

The OP wanted a solution in JavaScript. Not flash.

@MT, by "javascript" some people mean "in the browser client", so while JS-only might be a requirement, many of the people who chance upon this answer are really looking for JS-or-other-widely-supported-client-tech. Flash doesn't hit all platforms, but for a polish feature like clipboard support, it is worth adding if it improves the UX over a popup dialog (which it certainly does).

How do I copy to the clipboard in JavaScript? - Stack Overflow

javascript clipboard copy-paste
Rectangle 27 1

Here you go: a simple infallible script

The HTML is just to show an example. The gist is to add the JavaScript (+jQuery) and in your CSS, add to each li:hover a property li.hover like this:

#nav li:hover, #nav li.hover {
    /* your css */
}
/* timeout on hover: big menu */
var hoverTimeout; //declare timeout
$('#nav li').hover(function() { //mouse enter

  clearTimeout(hoverTimeout); //remove timeout, we're taking over control
  $('#nav li').removeClass('hover'); //clear all that are hovered
  $(this).parents('li').addClass('hover'); //add class to all our parents

},function() { //mouse leave

  var $this=$(this); //create local copy
  hoverTimeout = setTimeout(function() {
    $this.parents('li').removeClass('hover'); //un-hover all parents
  },1000); //1 second after we remove our mouse

});
@charset "UTF-8";

body {
  background: #aaa;  
}
nav {
  display: table-row;
    padding: 0;
    margin: 0;
    border: 0;
}
    nav a {
        display: block;
        line-height: 1em;
        text-decoration: none;
    }
    #nav, nav li {
        list-style: none;
        margin: 0;
        padding: 0;
    }
#nav {
    position: relative;
    z-index: 597;
    *display: inline-block;
    padding-left: .75rem;
    display: table-cell;
  width: 99%;
}
    #nav li {
        float: left;
        min-height: 1px;
        vertical-align: middle;
    }
    #nav li.hover, #nav li:hover {
        position: relative;
        z-index: 599;
        cursor: default;
    }
    #nav ul {
        visibility: hidden;
        position: absolute;
        top: 100%;
        left: 0;
        z-index: 598;
        width: 100%;
        bottom: 0;
        left: 0;
        margin-top: 0;
        text-transform: none;
        min-width: 210px;
    }

    #nav ul .hassubmenu>a:after {
        content: "+";
        float: right;
        width: 10px;
        text-align: center;
    }
    #nav ul .hassubmenu:hover>a:after, #nav ul .hassubmenu.hover>a:after { content: "-" }
        #nav ul ul {
            top: 0;
            left: auto;
            right: -99.5%;
        }
    #nav li.hover>ul, #nav li:hover>ul { visibility: visible }
    #nav ul, #nav {
        list-style-type: none;
        padding-left: 0;
    }
#nav>li {
    padding: .5rem;
    background: #ddd;
    border: #56a0d3 solid 2px;
    border-top: none;
    border-bottom: none;
}
  #nav>li+li { border-left: none }
  #nav>li a {
      color: #000;
      font-weight: 700;
      text-decoration: none;
  }
  #nav>li:hover>a, #nav>li.hover>a { opacity: 1 }
#nav ul li {
    position: relative;
    float: none;
    font-weight: 400;
    background: #fff;
    background: transparent\9;
    background: hsla(0,0,100%,.7);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#b2ffffff,endColorstr=#b2ffffff);
    zoom: 1;
    padding: 5px 10px;
}
  #nav ul li:nth-child(n) { filter: none }
  #nav ul li:hover, #nav ul li.hover { background: #fff }
    #nav ul li a { line-height: 1.2rem }
    #nav ul li:last-child>a { border-radius: 0 0 3px 3px }
#nav ul li ul li ul li li {
    background: #000;
    background: transparent\9;
    background: rgba(0,0,0,.7);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#b2000000,endColorstr=#b2000000);
    zoom: 1;
    border: 10px solid transparent;
    border-top: 1px solid #ddd;
    border-bottom: none;
}
#nav ul li ul li ul li li:nth-child(n) { filter: none }
#nav ul li ul li ul li li:first-child { border-top: none }
#nav ul li ul li ul li li:last-child { border-bottom: none }
#nav ul li ul li ul li li:hover, #nav ul li ul li ul li li.hover { background: #000 }
#nav ul li ul li ul li li a { color: #62a2d6 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
	<ul id="nav">

		<li class="hassubmenu">
			<a href="link">Menu-item</a>

			<ul>
				<li class="hassubmenu">
					<a href="link">Sub-menu-item</a>

					<ul>
						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>
					</ul>
				</li>

				<li>
					<a href="link">Sub-menu-item</a>
				</li>

				<li>
					<a href="link">Sub-menu-item</a>
				</li>
			</ul>
		</li>

		<li class="hassubmenu">
			<a href="link">Menu-item</a>

			<ul>
				<li class="hassubmenu">
					<a href="link">Sub-menu-item</a>

					<ul>
						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>
					</ul>
				</li>

				<li>
					<a href="link">Sub-menu-item</a>
				</li>

				<li>
					<a href="link">Sub-menu-item</a>
				</li>
			</ul>
		</li>

		<li class="hassubmenu">
			<a href="link">Menu-item</a>

			<ul>
				<li class="hassubmenu">
					<a href="link">Sub-menu-item</a>

					<ul>
						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>

						<li>
							<a href="link">Sub-sub-menu-item</a>
						</li>
					</ul>
				</li>

				<li>
					<a href="link">Sub-menu-item</a>
				</li>

				<li>
					<a href="link">Sub-menu-item</a>
				</li>
			</ul>
		</li>
	</ul>
</nav>

dropdown delay timeout jquery on hover - Stack Overflow

jquery hover timeout delay
Rectangle 27 1

JavaScript functions is called lamda in other functional language. It can be used to compose a new api (more powerful or complext function) to based on another developer's simple input. Curry is just one of the techniques. You can use it to create a simplified api to call a complex api. If you are the develper who use the simplified api (for example you use jQuery to do simple manipulation), you don't need to use curry. But if you want to create the simplified api, curry is your friend. You have to write a javascript framework (like jQuery, mootools) or library, then you can appreciate its power. I wrote a enhanced curry function, at http://blog.semanticsworks.com/2011/03/enhanced-curry-method.html . You don't need to the curry method to do currying, it just help to do currying, but you can always do it manually by writing a function A(){} to return another function B(){}. To make it more interesting, use function B() to return another function C().

function - JavaScript curry: what are the practical applications? - St...

javascript function currying partial-application
Rectangle 27 1

JavaScript functions is called lamda in other functional language. It can be used to compose a new api (more powerful or complext function) to based on another developer's simple input. Curry is just one of the techniques. You can use it to create a simplified api to call a complex api. If you are the develper who use the simplified api (for example you use jQuery to do simple manipulation), you don't need to use curry. But if you want to create the simplified api, curry is your friend. You have to write a javascript framework (like jQuery, mootools) or library, then you can appreciate its power. I wrote a enhanced curry function, at http://blog.semanticsworks.com/2011/03/enhanced-curry-method.html . You don't need to the curry method to do currying, it just help to do currying, but you can always do it manually by writing a function A(){} to return another function B(){}. To make it more interesting, use function B() to return another function C().

function - JavaScript curry: what are the practical applications? - St...

javascript function currying partial-application
Rectangle 27 2

Since Javascript is a prototypical language, it doesn't have the same sort of class inheritance that a language like, say, Java has. If you want a very simple instance of inheritance, you could try something like:

function baseservice() {
  this.loadAnimate = function () {
    $('#ajax-spinner').show();
  };
  this.loadComplete = function () {
    $('#ajax-spinner').hide();
  };
  this.apiEndpoint = function() {
    return "http://api.com/api/";
  };
};

var documentservice = new baseservice();
documentservice.sendRequest() = function() { /* ... */ }

Then, documentservice has all of baseservice's members (note the this. in baseservice's function declaration instead of var).

If you don't want to have to use the new keyword, you can create a function extend either adds a field pointing to baseservice (document.baseservice = baseservice) or does a deep (recursive) copy, then adds documentservice.sendRequest.

Of course, folks have already worked on this with things like ded/klass.

JS works very differently to classical inheritance languages. Strongly advice that the OP read Crockford's "JavaScript the Good Parts" book. amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/

jquery - Simple Example of Javascript Inheritance? - Stack Overflow

javascript jquery
Rectangle 27 1

var REPLACEMENTS = {
    'example-phrase': 'Example Phrase',
    'example2-phrase': 'Example 2 Phrase',
    'example-solution': 'Example & Solution'
}

function doReplacement(input) {
    for (var key in REPLACEMENTS) {
        input = input.replace(key, REPLACEMENTS[key]);
    }

    return input;
}

Might not be the most performant solution though. You might need to ask yourself: Do you need case insensitivity? Can a single input contain more than one of the strings that need to be replaced? Is the string itself exactly equal to the replacement key or does it contain it?

h2
$(function() {
    var REPLACEMENTS = {
        'example-phrase': 'Example Phrase',
        'example2-phrase': 'Example 2 Phrase',
        'example-solution': 'Example & Solution'
    }

    function doReplacement(input) {
        for (var key in REPLACEMENTS) {
            input = input.replace(key, REPLACEMENTS[key]);
        }

        return input;
    }

    $('h2').each(function() {
        var $this = $(this);
        $this.html(doReplacement($this.html()));
    });
});

Exactly how you have it is how I would need it. The string getting replaced are always the same and what needs to replace them is always the same. What about this code is a performance hindrance?

It depends on how often you will run this and how many replacements there will be. If you this with, say, 20 headlines and 50 possible replacements you don't really need to care about its performance. It might become an issue if you run this over thousands of texts with hundreds of replacements.

Ah, luckily just running on 1 page and probably only 10-20 replacements will happen. Do I need some other code to have this run automatically as soon as the page loads?

Perfect! Thank you. Answered accepted, exactly what I needed. I did have to change $ to jQuery for no conflict (I couldn't determine what other script was causing it) and changed h2 to .replacement so I could apply this function with a css class. jsfiddle.net/codeview/GSZLR

Simple/Basic Jquery or Javascript String Replace for Multiple Values -...

javascript jquery str-replace
Rectangle 27 7

Simplicity is best here. I've used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.

var values = $(this).serialize(),
attributes = {};

values.replace(/([^&]+)=([^&]*)/g, function (match, name, value) {
    attributes[name] = value;
});

json - Convert form data to JavaScript object with jQuery - Stack Over...

jquery json serialization
Rectangle 27 7

Simplicity is best here. I've used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.

var values = $(this).serialize(),
attributes = {};

values.replace(/([^&]+)=([^&]*)/g, function (match, name, value) {
    attributes[name] = value;
});

json - Convert form data to JavaScript object with jQuery - Stack Over...

jquery json serialization
Rectangle 27 7

Simplicity is best here. I've used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.

var values = $(this).serialize(),
attributes = {};

values.replace(/([^&]+)=([^&]*)/g, function (match, name, value) {
    attributes[name] = value;
});

json - Convert form data to JavaScript object with jQuery - Stack Over...

jquery json serialization
Rectangle 27 8

Example of tj111 suggestion:

$("#ConditionValue").val(
    (
        new Date(
            "01/01/2000 " + 
            $("#EventCloseTimeHour option:selected").text() +
            $("#EventCloseTimeMin option:selected").text() + ":00" +
            " " +
            $("#EventCloseTimeMeridian option:selected").text()
        )
    ).toTimeString().slice(0,8))
;
hour = hour %12 + (meridian === "AM"? 0 : 12);
hour = hour < 10 ? "0" + hour : hour;

I like yours the best so far but I get invalid date out of "toTimeString" and then It slices it up to just say "Invalid ". This is firefox with firebug, but it doesn't work in chrome either. I don't think the date object takes meridians

Check if you get the right values from the jquerys... If the input is invalid you get an invalid output.

@someplease don't recommend parsing with the built-in parser, it's implementation dependent and very error prone, per Why does Date.parse give incorrect results? Also, toTimeString is implementation dependent and may not return the required value.

Sure @RobG. Do you know where I can find a flux capacitor for my time machine, so that I can go back in time to February 2009 ?

jquery - What's a simple way to convert between an am/pm time to 24 ho...

javascript jquery time
Rectangle 27 8

Example of tj111 suggestion:

$("#ConditionValue").val(
    (
        new Date(
            "01/01/2000 " + 
            $("#EventCloseTimeHour option:selected").text() +
            $("#EventCloseTimeMin option:selected").text() + ":00" +
            " " +
            $("#EventCloseTimeMeridian option:selected").text()
        )
    ).toTimeString().slice(0,8))
;
hour = hour %12 + (meridian === "AM"? 0 : 12);
hour = hour < 10 ? "0" + hour : hour;

I like yours the best so far but I get invalid date out of "toTimeString" and then It slices it up to just say "Invalid ". This is firefox with firebug, but it doesn't work in chrome either. I don't think the date object takes meridians

Check if you get the right values from the jquerys... If the input is invalid you get an invalid output.

@someplease don't recommend parsing with the built-in parser, it's implementation dependent and very error prone, per Why does Date.parse give incorrect results? Also, toTimeString is implementation dependent and may not return the required value.

Sure @RobG. Do you know where I can find a flux capacitor for my time machine, so that I can go back in time to February 2009 ?

jquery - What's a simple way to convert between an am/pm time to 24 ho...

javascript jquery time
Rectangle 27 3

You can compare Javascript and Jquery because jQuery is a library which minimizes the complex javascript code into the simple methods and properties. You can explain jquery in a single line Write less do more but not AngularJS Framework.

DOM Manipulation is a powerful feature which is given by jQuery. You can manipulate DOM elements change the styling of a page. Play a Hide-and-Seek withe DOM elements, and many more. There is no templating like feature, all you need to code your application according to you requirement. For example, if you want to bind a keyup event to a textbox and wanted to display the changed value in a span then you need to write code like,

$('input').on('keyup',function(){
    $('span').text(this.value);
)};

On the other end Data Binding is a powerful feature which can be accomplished by AngularJs. This type of framework are commonly used for SPA(Single Page Applications), where data binding is must for example, online test. The advantage of using the Framework is that you will get the template including the framework. So you can bind the elements together by using ng- module like,

<input type='text' ng-model='inputElem'>
<span ng-bind='inputElem'></span>

And, I think the comparison can be,

  • Javascript and Jquery
  • Jquery and Angular (Not Javascript and Angular)

One more thing here, Javascript is a language, Jquery is a library and Angular is a Framework.

Below are the links which will clear more about library and framworks,

jquery - Comparing JavaScript vs AngularJS? - Stack Overflow

javascript jquery angularjs html5
Rectangle 27 1

If all you need to do is wait for the html on the page to become stable before trying to interact with elements, you can poll the DOM periodically and compare the results, if the DOMs are the same within the given poll time, you're golden. Something like this where you pass in the maximum wait time and the time between page polls before comparing. Simple and effective.

public void waitForJavascript(int maxWaitMillis, int pollDelimiter) {
    double startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime + maxWaitMillis) {
        String prevState = webDriver.getPageSource();
        Thread.sleep(pollDelimiter); // <-- would need to wrap in a try catch
        if (prevState.equals(webDriver.getPageSource())) {
            return;
        }
    }
}

I would like to note here that I logged the time it took to poll a medium size page twice, then compare those strings in java and it took a little over 20ms.

At first I found this to be a dirty solution, but it seems to work great and it doesn't involve setting variables client side. One caveit might be a page which is constantly being changed by javascript (i.e. a javascript clock) but I don't have that so it works!

java - Selenium WebDriver : Wait for complex page with JavaScript(JS) ...

java selenium webdriver selenium-webdriver