Dec. 4th, 2007
Getting PHP arrays to work in jQuery
Dec. 4th, 2007 06:36 pmMaking form variables into arrays in PHP easy. One only needs to add "[]" to the name of the variable to make this happen. Example:
Lately, I've been using jQuery in some of my web development. It lets me "do more with less", as they say. One very easy way to access specific HTML entities in a document is with pound-notation. Examples:
It took me some time, but I finally found a workaround, which was the real reason behind writing this journal entry -- so as to save myself and other folks time from having to find this solution again in the future. Examples:
<input type="text" name="search[name]" id="search[name]" />
<input type="text" name="search[age]" id="search[age]" />
<input type="text" name="search[city]" id="search[city]" />
<input type="text" name="search[state]" id="search[state]" />
<input type="text" name="search[country]" id="search[country]" />
When the form is submitted and the PHP code on the processing page is run, there will be a handy little array called $search. This variable can then be passed into additional functions, looped through, etc. It's way easier than working with 5 separate variables.<input type="text" name="search[age]" id="search[age]" />
<input type="text" name="search[city]" id="search[city]" />
<input type="text" name="search[state]" id="search[state]" />
<input type="text" name="search[country]" id="search[country]" />
Lately, I've been using jQuery in some of my web development. It lets me "do more with less", as they say. One very easy way to access specific HTML entities in a document is with pound-notation. Examples:
$("#foo").addClass("required");
$("#bar").hide();
$("#username").css("background-color", "blue");
If you just groaned, then you know what's coming. Sure enough, jQuery has issues with using square brackets in pound-notation. It seems that square brackets are used by jQuery itself as attribute selectors.$("#bar").hide();
$("#username").css("background-color", "blue");
It took me some time, but I finally found a workaround, which was the real reason behind writing this journal entry -- so as to save myself and other folks time from having to find this solution again in the future. Examples:
$("[id='search[name]']").hide();
$("[id='search[address]']").show();
$("[id='search[country]']").css("color", "green");
That's about it. Happy jQuerying!$("[id='search[address]']").show();
$("[id='search[country]']").css("color", "green");