how to set radio checked of an input by .val()? - javascript

i want to select an input by his value.
the problem is that i got a 4 radio inputs
and when the user clicks "next" it saves the value of that answer in AnsW array.
and when the user clicks "back" i want the input radio button with the value that i have in my AnsW array to be checked, so the user can know what he has selected and change his answer to something else.
html code:
<ul>
<li class="li0">
<input type="radio" value="ch1" name="choice" id="li0"/>
<label for="li0"></label>
</li>
<li class="li1">
<input type="radio" value="ch2" name="choice" id="li1"/>
<label for="li1"></label>
</li>
<li class="li2">
<input type="radio" value="ch3" name="choice" id="li2"/>
<label for="li2"></label>
</li>
<li class="li3">
<input type="radio" value="ch4" name="choice" id="li3"/>
<label for="li3"></label>
</li>
</ul>
my code is:
function go_back(){
$("#back").bind("click",function(){
qNum--;
showQuestion(qNum);
if(AnsW.length === 0){
calcAnswers--;
}
alert(AnsW[qNum]);
tempAns = AnsW[qNum];//user last answer which is false i need this to make the radio button point to that answer
//alert( $("input[value='tempAns']"));
$("input").val(tempAns).attr('checked', true);
alert(tempAns);
//alert(tempAns);
AnsW.splice(-1,1);//delete the false answer from the array i need this to make sure that the answer is deleted and there wont be overload of wrong answers
//alert(deleteAns);
if(qNum === 0){
$("#back").css({"visibility":"hidden"})
}
});
}

jQuery selectors allow you to find elements based on their attributes, an exact match example:
$("element.class[attribute=value]")
Check the value attribute in the selector
$("input[value="+tempAns+"]").prop('checked', true)

Related

Javascript : Change button text according to hidden variable value

i have hidden variable with default value "on" , i want to change the text of another button from Disable to Enable according to this hidden value , if the hidden field value is "on" the button text is "Disable" and vice verse . i have tried but my solution doesn't work
hidden field
<input name="hiddenV" type="hidden" id="hiddenValue<%=ud.getUserId()%>" value="on" />
button
<input type="button" id="delUserButton<%=ud.getUserId()%>" onclick="openDelDiv(<%=ud.getUserId()%>, '<%=ud.getUserName()%>'); change(this.id);" value="Disable"/>
js function
function change(btn) {
var hiddenValue = document.getElementsByName("hiddenV")[0];
var disButton = document.getElementById(btn);
if (hiddenValue.value === "on")
disButton.value = "Disable";
else
disButton.value = "Enable";
}
OpendelDev() : it's a popup dialog like ( are you sure you want to disable this user) with ok button that causes the page to reload
function openDelDiv(userId, userName) {
$("#userId_delete").val(userId);
$("#userName_delete").text(userName);
$("#delUserDiv").bPopup();
}
but put in mind that the button is placed in for loop inside a jsp page so the id for every button will be different
I think you are actually faking a <input type="radio"/> here.
The goal is then to have an input for each possible value, along with a list of buttons to toggle them. Then, all you have to do is show the buttons you want (ie: show "enable" button if status "disabled" is checked and vice-versa).
<input type="radio" class="input-field" name="status" value="enabled" checked="checked" id="a"/>
<input type="radio" class="input-field" name="status" value="disabled" id="b"/>
<ul class="buttons">
<li>
<label class="enabling" for="a">
<button>Enable</span>
</label>
</li>
<li>
<label class="disabling" for="b">
<span>Disable</span>
</label>
</li>
</ul>
In CSS:
.input-field[value="enabled"]:checked ~ ul.buttons label.enabling,
.input-field[value="disabled"]:checked ~ ul.buttons label.disabling {
display: none;
}
(not actually run & tested, but the spirit is there)

Tick checkbox via javascript console by lable names

I would like to check boxes via javascript.
The thing is I have a task to check more then 300 checkboxes whith specific names.
I can check one box, or check all boxes... but how to check specific boxes?
Here is an example:
<li id="s1" class="city-select">
<input name="rid" id="r1" value="1" type="checkbox">
<label for="r1" id="l1">Paris</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r2" value="2" type="checkbox">
<label for="r2" id="l2">Plovdiv</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
I would like to tick only "Berlin" and "Paris" - here is what I'm using to tick all:
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});
And here is what am I trying to type:
$("lable:contains('paris, berlin')").prev().find('input').addAttr("checked");
You have wrong selector to target checkboxes. You need to use:
$("label:contains(Paris),label:contains(Berlin)").prev().prop("checked",true);
Working Demo
Update:
var cities = ["Paris","Berlin"];
$("label:contains('" + cities.join("'),label:contains('") + "')").prev().prop("checked",true);
Working Fiddle for update
It looks like your use of prev should be parent or closest.
So you take the current label, go up to the container, then down to the checkbox.
If you use prev then you restrict how much you can change the html (eg if you add a div wrapper around the label in the future, you'll have to change all your code).
given:
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
then use
$("label:contains(Paris),label:contains(Berlin)")
.closest("li")
.find(":checkbox")
.prop("checked",true);
More info at the API documentation: https://api.jquery.com/closest/
How to use this for 300 cities?
This depends on how they are stored. If it's a comma separated list (Paris,Berlin) then split into an array first, if it's json, then convert to an array first...(see the pattern?)
var citiesList = "Paris,Berlin".split(",");
$(citiesList).each(function() {
$("label:contains(" + this + ")")
.closest("li")
.find(":checkbox")
.prop("checked",true);
});

how to set checked radio button by checking another radio button

I have 2 seperate fields with 4 radio buttons each.
Field nr1 has radio button unchecked by using jquery, field nr2 has the first radio button checked by default.
What i need is, if in field nr1 a radio button is checked, then it checks the same radio button in field nr2.
Here is how my html looks like:
<p class="form-row form-row-wide validate-required" id="billing_piegadatajs_field"><label for="billing_piegadatajs" class="">Piegādes veids <abbr class="required" title="vajadzīgs">*</abbr></label><br>
<input type="radio" name="billing_piegadatajs" value="Pasta Stacija" class="radio" style="width:10%" checked="checked"><span for="billing_piegadatajs">Pasta Stacija</span><br>
<input type="radio" name="billing_piegadatajs" value="Post24" class="radio" style="width:10%"><span for="billing_piegadatajs">Post 24</span><br>
<input type="radio" name="billing_piegadatajs" value="Kurjerdienests" class="radio" style="width:10%"><span for="billing_piegadatajs">Kurjerdienests</span><br>
<input type="radio" name="billing_piegadatajs" value="Saņemt uz vietas" class="radio" style="width:10%"><span for="billing_piegadatajs">Saņemt uz vietas ( Saldū )</span>
</p>
<br>
<tr class="shipping">
<th>Piegādes izmaksas</th>
<td>
<ul id="shipping_method">
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" checked="checked" class="shipping_method">
<label for="shipping_method_0_flat_rate">Pasta Stacijas: <span class="amount">€ 3.50</span></label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_international_delivery" value="international_delivery" class="shipping_method">
<label for="shipping_method_0_international_delivery">Post 24: <span class="amount">€ 3.50</span></label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_apg_shipping" value="apg_shipping" class="shipping_method">
<label for="shipping_method_0_apg_shipping">DLW Kurjeris: <span class="amount">€ 9.00</span></label>
</li>
<li>
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_pickup" value="local_pickup" class="shipping_method">
<label for="shipping_method_0_local_pickup">Uz vietas - Saldū (Bez maksas)</label>
</li>
</ul>
</td>
</tr>
I use this jquery to uncheck the field nr1 radio button when page is loaded.
jQuery(document).ready(function(){
jQuery('#billing_piegadatajs_field')
jQuery('#billing_piegadatajs_field').find('input[name="billing_piegadatajs"]').each(function() {
jQuery(this).prop('checked', false);
});
});
Here is a link to jsfiddle
You can acheive this in many many ways
One approach should be considering 2 set of radio
you have 2 sets already :
the first one share the class name 'radio'
the second one share the class name 'shipping_method'
The logic
1) add a click event on all radio of the first set
2) Get the order rank of the one we click on
3) force a click event on the radio button having the same index in the second set
// Track the click on the first set of radio
jQuery('.radio').on('click',function(){
// Get the element index , which one we click on
var indx = jQuery(this).index('.radio');
// Trigger a click on the same index in the second radio set
jQuery('.shipping_method')[indx].click();
})
there is the jsfiddle : http://jsfiddle.net/MMJRk/21/
First you need to find out which box is checked. The following link may help.
In jQuery, how do I select an element by its name attribute?
Then you need to loop through the next check boxes, comparing the value to the value you want for each box. When you find the one you want. Check that one.
Link for how to check box.
How to check a radio button with jQuery ?
Well, i have to admit it is not the most ideal way of getting what you want. But it does the trick: http://jsfiddle.net/veritas87/MMJRk/25/
jQuery('p.form-row input[type=radio]').on('change', function () {
var radioNumber = $(this).index('.radio');
$("ul#shipping_method input[type=radio]:eq(" + radioNumber + ")").prop('checked', true);
});
In short, when a radiobutton changes in p.form-row it will get the index of the clicked radiobutton and it will set the radiobutton in the second list of radiobuttons to checked.
I've updated your jsfiddle and now it works.
Basically, I assigned to each input (and its counterpart), an index using custom data attributes (data-index). I attached an event handler to the first group of inputs, and, based on the index of the checked one, I check the correct radiobutton in the second group:
$('#billing_piegadatajs_field input[type="radio"]').on('change', function() {
if (!this.checked) return;
var index = this.getAttribute('data-index');
$('#shipping_method input[data-index="' + index + '"]').prop('checked', true);
});

Happy.js radio button validation

Here is my radio buttons list:
<ul>
<li>
<input id="radio_1" type="radio" name="radio-button" />
<label for="radio_1">Radio 1</label>
</li>
<li>
<input id="radio_2" type="radio" name="radio-button" />
<label for="radio_2">Radio 2</label>
</li>
</ul>
I'm validating these radio inputs via Happy.js (http://happyjs.com/). I'm trying to check if any radio is checked. If neither is checked, than show single error message.
The problem is that Happy.js generates error messages for every radio input.
Here is fiddle -- http://jsfiddle.net/HhZtF/
The problem is in your error function.
function getError(error) {
return $('<div id="' + error.id + '" class="hint error">' + error.message + '</div>');
}
You should update a 'status' div ID .
For example have a div where you want the error.
<div id="formError"></div>
This should be display:none; by default.
Then in your error function you will update this area.
function getError(error) {
$('#formError').append( '<span class="error">This is an error - something is missing</span>' );
$('#formError').show(); // This will display the error box.
}
Something like this will help. Of course you will need to do a bit more but you should get the idea.
Also this assumes you are using jQuery also, but you added it as one of your tags so i took the liberty of taking it for granted.
The happy.js provides the errorTarget method. You can use it to specify error location.
errorTarget (string): Selector to use in lieu of the input element itself when choosing where to insert the error html. Error html will be inserted .after() this selector
Final code
<ul id="single-error">
<li>
<input id="radio_1" type="radio" name="radio-button" />
<label for="radio_1">Radio 1</label>
</li>
<li>
<input id="radio_2" type="radio" name="radio-button" />
<label for="radio_2">Radio 2</label>
</li>
</ul>
And then in your js you will have
$('#form').isHappy({
fields: {
' input[name=radio-button]': {
required: 'sometimes',
message: 'Error',
test: function () {
return $('input[name=radio-button]').is(':checked');
},
errorTarget: '#single-error'
}
}
});

More efficient way to use document.getElementById for checkboxes?

This section of code uses jQuery to hide/show form fields. When they are hidden the values of those fields are set to empty. This is easy for an input field with its unique ID. I run into trouble with checkboxes. The code below works for three checkboxes. But I have to use this same technique for a set of 26 checkboxes. How can I do this more efficiently?
$(".transfer").click(function(){
if ($('input[name=transfer_position]:checked').val() == "yes" ) {
//Slide Down Effect
$(".transfer_details").slideDown("slow");
document.getElementById('transfer_interest').focus();
} else {
//Slide Up Effect
$(".transfer_details").slideUp("slow");
document.getElementById('transfer_interest').value = "";
document.getElementById('select_positions_0').checked = false;
document.getElementById('select_positions_1').checked = false;
document.getElementById('select_positions_2').checked = false;
}
});
<li>
<label>
<input type="radio" name="transfer_position" class="transfer" value="yes" id="transfer_position_0" />
Yes</label>
<label>
<input type="radio" name="transfer_position" class="transfer" value="no" id="transfer_position_1" />
No</label>
</li>
<li class="transfer_details">
<label for="transfer_interest">Why are you interested in transferring to your selected SL positions and what would you bring to that position(s) and team(s)?</label>
<textarea name="transfer_interest" id="transfer_interest" cols="80" rows="6"> </textarea>
</li>
<li class="transfer_details">
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Resident Advisor" id="select_positions_0" />
Resident Advisor</label>
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Programming Assistant" id="select_positions_1" />
Programming Assistant</label>
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Social Justice Advocate " id="select_positions_2" />
Social Justice Advocate </label>
</li>
Use classes, since many elements can share a class. So you simply uncheck all checkboxes with a certain class:
$('.select_positions').attr('checked', false);
Use the amazing power of jquery's selectors, of course!
$('li.transfer_details input[type=checkbox]').prop("checked", false);
descendant selector - http://api.jquery.com/descendant-selector/
setting the checked attribute -
http://api.jquery.com/prop/
One approach would be to use the child selector in conjunction with the checkbox selector, and iterating using the each function in jQuery to accomplish what you're looking for.
Keep in mind this is untested, so its probably going to raise errors and I trust you to fix that.
Beneath your slide up effect, you'd want something like the following:
$('.transfer_details > input:checkbox').each(function() {
(this).checked = false;
});
Hope this helps and happy coding!

Categories

Resources