jQuery way to handle select lists, radio buttons and checkboxes - javascript

When I handle HTML form elements with jQuery, I always end up with an ugly mix of jQuery syntax and plain JavaScript like, e.g.:
function doStuff($combo){
if( $combo.get(0).options[$combo.get(0).selectedIndex].value=="" ){
var txt = "";
}else{
var txt = $combo.get(0).options[$combo.get(0).selectedIndex].text;
}
var $description = $combo.closest("div.item").find("input[name$=\[description\]]");
$description.val(txt);
}
Are there standard jQuery methods to handle typical operations on elements like <select>, <input type="radio"> and <input type="checkbox">?
With typical, I mean stuff like reading the value of the selected radio button in a group or replacing elements in a selection list. I haven't found them in the documentation but I admit that method overloading can make doc browser kind of tricky.
Update
Thanks everyone. Once in the right track, I figured out myself the rest of the stuff. E.g., I can handle a <select> list like any other DOM tree:
$("select")
.empty()
.append('<option value="">(Pick one)</option><option value="a">Option A</option><option value="b">Option B</option>');

Yes, you should be able to simplify your code a lot. Here are a few examples of working with form elements:
<input type="text">
$(':text') // select all text boxes
$('input#example').val(); // gets value of a text box
<input type="checkbox">
$(':checkbox') // selects all checkboxes
$('input.example:checked') // selects all ticked checkboxes with class 'example'
$('#example').is(':checked'); // true if checkbox with ID 'example' is ticked
<input type="radio">
$(':radio') // selects all radio buttons
$(':radio:checked').each( function() {
$(this).val(); // gets value of each selected radio button
});
$('input:radio[name="asdf"]'); // gets particular group of radio buttons
<select>
$('select#example').change( function() {
// this part runs every time the drop down is changed
$(this).val(); // gets the selected value
});
See also http://api.jquery.com/category/selectors/form-selectors/ for more selectors.

Since you want the text and not the value, use .text() for that <option> (find it using the :selected selector), like this:
function doStuff($combo){
var txt = $combo.children("option:selected").text();
$combo.closest("div.item").find("input[name$=\[description\]]").val(txt);
}
If you wanted the value part of <option value="4" selected>Four</option> then you could use .val(), like this:
var val = $combo.val();

For <select> elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).

For selects you can use the val() method. In case of multiple select the val() method returns an array of the selected options.
For checkboxes and radio you can grab all the selected checkboxes using the :checked selector.
You'll find all the details as well as examples at the jQuery site : http://api.jquery.com/val/

For Select elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
Ignore formatting....i havent done that..;)

Related

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

jQuery Autopopulate Multiple Select uses text instead of value

I've got a multiple select like this configured to auto-populate:
<select id="multiple-select-box" class="selectivity-input" data-placeholder="Type to search condos" multiple>
<option id="Alabama Grove Terrace" value="Alabama Grove" >Alabama Grove Terrace</option>
<option id="Alden Pines" value="Alden Pines" >Alden</option>
</select>
Upon select I realized the script is submitting the visible Text for each option instead of the value="" for each option chosen.
I tried to change var t=$(this).text(); to var t=$(this).value(); thinking that would grab the value instead of the option text but had the same results. What am I missing?
<script>
$(document).ready(function() {
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).text();
//if()
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
})
$('#multiple-select-box').selectivity();
});
</script>
Ok, so I went to check this selectivity plugin you're using and it converts your select into a series of divs as
<div class="selectivity-results-container">
<div class="selectivity-result-item highlight" data-item-id="Alabama Grove">Alabama Grove Terrace</div>
<div class="selectivity-result-item" data-item-id="Alden Pines">Alden</div>
</div>
you have to change your submit function to get the data-item-id property which corresponds to your original select value like
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).data("item-id");
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
edit
fiddle example
In this line, you are appending options to the select, but you have set no value attribute:
$(".ml").append("<option selected='selected'>"+t+"</option>");
As stated in the comments, the "fetch value" method of a form element in jQuery is:
$(this).val()
You might be confusing it with the JavaScript property:
this.value
...which also works. Both return an array of strings if something is selected and set to "multiple"
To follow up on your comment, I don't see your markup for the selected element with class="ml" thus it's almost impossible to debug why your form isn't submitting the values without seeing the bigger picture (i.e. it may be outside the form element). You could try adding the value property to the select element however jQuery should be able to pick up selected options missing the value property by using the text value instead.

Show a text box based on select box value

I am wondering if someone could help me understand how I can achieve this. I want to show two input boxes only when a certain value in a select box is chosen using javascript (inc jquery).
My select box has this value:
<select name="menu-168" class="wpcf7-validates-as-required">
<option value="Residential">Residential</option>
<option value="Commercial">Commercial</option>
</select>
My input box has this value:
<input type="text" name="text-708" value="" class="wpcf7-validates-as-required" size="40">
In Pseudo code I am after something like this:
<if select name="menu-168" value = "Commerical">
<add css property ".hidden" to input name="text-708">
</if>
My javascript knowledge is so poor, would anyone mind showing me how this is done? This is a JSfiddle with the relevant HTML:
http://jsfiddle.net/K9zGP/
This is using jQuery:
if ($("select[name='menu-168']").val() == "Commercial") {
$("input[name='text-708']").addClass("hidden");
}​
On a side note, i would advise you to use class instead of names for referencing HTML elements. Class selection is much faster than attributes.
You can use .on() to attach a listener on the select, to listen for a change event. With the change-event listener you can act whenever someone changes the selected option. Then you can use .toggle() to show/hide the input, depending on what the user has chosen in the select-list.
Something like this:
​$(function(){
$("select[name='menu-168']").on("change", function (){
$("input[name='text-708']").toggle($(this).val() !== "Commercial");
});
});​
Working example
In this example I use attribute selectors to select your elements, because there is nothing more exact to go on, but you could get slightly better performance by adding ID's to the relevant elements and use those for the selectors instead.
$('#menu-168').on('change', function(){
($this).val() = "Commericial" ?
$('input[name='text-708']').show() : $('input[name='text-708']').hide();
}
})

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Headaches with radios in Jquery

I have 2 radios:
<input id="a_15_0" type="radio" value="abc" name="a_15"/>
<input id="a_15_1" type="radio" value="xyz" name="a_15"/>
Both are unselected. I have only the name of the radio, i.e a_15, but not the IDs.
1) How can I get the value of the selected option of this radio? E.g if the user clicked 'xyz', how can I get it? Right now I'm using:
var val=$('[name="a_15"]').val();
Which always gives abc even when xyz is selected.
2) How can I get xyz to be selected through javascript, without knowing the ID of the radio which says xyz? Doing:
$('[name="a_15"]').val('xyz');
Changes the value of both radios to xyz rather than selecting the one whose value had been xyz.
Do I need to use document.myForm.a_15.value? Would that work consistently?
1)
try
var val = $('input[name=a_15]:checked').val();
jQuery docs on checked pseudo-class
2) the only solution I found is
$('input[name=a_15][value=xyz]').get(0).checked=true
Have you tried using the val() in conjunction with the :checked selector?
$('[name="a_15"]:checked').val();
As for setting the selection based on the value, you may have to perform a multiple attribute tests?
$('[name="a_15"][value="xyz"]').get(0).checked = true;
There are many ways of selectors in jQuery; id, class, etc..I believe this will do the job, not tested:
var val= $("input[name=a_15]:checked").val();
if you know the name of the form then this will definitely do it
var val= jQuery('#radio_form input:radio:checked').val();
you have the correct code here:
to run
to edit
the correct form is:
$("input[name='a_15']:checked").val();
as you can test using the links above

Categories

Resources