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);
});
Related
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);
});
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)
So I have a kind of problem: I need to remove "information" from tag to tag including text between it.
So somewhere in html is:
<input type="radio" rel="1" value="Surname1" name="lastnames">Surname1<br>
<input type="radio" rel="2" value="Name2" name="lastnames">Name2<br>
<input type="radio" rel="3" value="lol" name="lastnames">lol<br>
<input type="radio" rel="4" value="lol2" name="lastnames">lol2<br>
And for example:
var current_id = $('input:checked:radio').attr('rel');
$.get('index.php?delete_by_id='+current_id);
$("input:radio[rel='"+current_id+"']").remove();
So, after the GET to php is sent, I need to delete from the radio list deleted item. With input all ok, but with name next to him I have problems...
PS.
I know, that situation is stupid, but I don't have any time to rewrite it until tomorrow (exams)
Wrap the label with a span element.
<input type="radio" rel="1" value="Surname1" name="lastnames"><span>Surname1</span><br>
<input type="radio" rel="2" value="Name2" name="lastnames"><span>Name2</span><br>
Then while deleting, Get the next span and remove it as well
var item=$('input:checked:radio');
var current_id = item.attr('rel');
$.get('index.php?delete_by_id='+current_id,function(data){
item.remove();
item.next("span").remove();
});
It is always a good practice to keep HttpPost Operations for Delete/Update functions. Otherwise anybody can delete a record from your database if they know the item id, by simply executing your page with those querystrings in the browser.
Not sure exactly what you are trying to do and/or why it is not working, but consider writing the code like this:
var $selected_radio = $('input:radio:checked'); // store element reference
$.get('index.php?delete_by_id=' + $selected_radio.attr('rel'), function() {
// use a callback function to only remove if code succeeds
$selected_radio.remove();
});
EDIT: Looking back I see you want to remove the input along with its label. You just need to fix your HTML to be what it actually should be:
<label>
<input type="radio" rel="1" value="Surname1" name="lastnames"> Surname1
</label>
Which then makes the remove code in jQuery look like:
$selected_radio.closest('label').remove();
I ussually always use a label, to show text that is connected to a radio button:
<input id="radio1" type="radio" rel="1" value="Surname1" name="lastnames"><label for="radio1">Surname1</label><br>
<input id="radio2" type="radio" rel="2" value="Name2" name="lastnames"><label for="radio2>Name2</label><br>
<input id="radio3" type="radio" rel="3" value="lol" name="lastnames"><label for="radio3">lol</label><br>
<input id="radio4" type="radio" rel="4" value="lol2" name="lastnames"><label for="radio4">lol2</label><br>
Then you can do like this in your javascript code:
var current_rel = $('input:checked:radio').attr('rel'),
current_id = $('input:checked:radio').attr('id');
$.get('index.php?delete_by_id='+current_rel);
$('#' + current_id + ', label[for="' + current_id + '"]).remove();
I'm trying to grab the value of a hidden field that resides above each group of LI's with javascript, I cannot use jQuery because of an unreasonable client's concerns (believe me, I've tried, they just don't want to "risk" adding a library)... anyway...
The list would look something like this:
<input id="hidden1" type="hidden" value="5" class="includeds">
<h3>header</h3>
<ul class="groups">
<li><input id="li1" type="checkbox" value="1" onclick="value()"></li>
<li><input id="li2" type="checkbox" value="2" onclick="value()"></li>
<li><input id="li3" type="checkbox" value="3" onclick="value()"></li>
</ul>
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value()"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value()"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value()"></li>
</ul>
So if I click on checkbox li1, I want to retrieve the value "5" from the hidden field above it.
If I click li5, I want to get the value of "2" from the first hidden field above it, etc, etc.
in a previous SO question some amazing people helped me do this with jQuery:
if($(this).closest('ul').prevAll('.includeds:first').val() !== '0') {
// logic here
}
but when presented to the client, I ran into the aforementioned complaints. So now I need to do the same thing with javascript vanilla. I appreciate any help or pointers you guys could provide. I apologize for asking the same question twice, between jquery and javascript.
Uhm, the jQuery code I'd use would be:
$(this).parent().prev().prev().val()
With that in mind, all you have to do is rewrite the code to correct plain javascript entities.
The result would be something like:
function getParent(node){
return node.parentNode;
}
function getPrev(node){
do { // loop to find the previous node that is an element
node = node.previousSibling;
}while(node && node.nodeType != 1);
return node;
}
getPrev(getPrev(getParent(this))));
If you can't use jQuery then complex queries like the on you mentioned become much more difficult. In liue of jQuery it's easiest to reference elements by their ID tag or by a class filter (depending on the scenario).
Here i would say the best bet is to hard code the given input ID into the onclick function.
HTML
<input id="hidden2" type="hidden" value="3" class="includeds">
<h3>header2</h3>
<ul class="groups">
<li><input id="li4" type="checkbox" value="4" onclick="value('hidden2')"></li>
<li><input id="li5" type="checkbox" value="5" onclick="value('hidden2')"></li>
<li><input id="li6" type="checkbox" value="6" onclick="value('hidden2')"></li>
</ul>
JavaScript
function value(id) {
var elem = document.getElementByID(id);
...
}
I am having some difficulty in using the jQuery Validator plugin. I have a list of checkboxes with different name attributes and I can't seem to figure out how to ensure that at least one of them has been checked. Everything that I find on Google seems to only work when the name attribute is the same.
Here is some sample code (updated):
<ul id="email_lists">
<li>
<input name="checkbox1" type="checkbox" /> List 1
</li>
<li>
<input name="checkbox2" type="checkbox" /> List 2
</li>
<li>
<input name="checkbox3" type="checkbox" /> List 3
</li>
<li>
<input name="checkbox4" type="checkbox" /> List 4
</li>
</ul>
I want to make sure that at least one of those is checked. Unfortunately, I cannot make the names the same as it is form that submits to a third-party email marketing application and it is expecting specific name attributes for these checkboxes.
Update
I am aware of how to do this using plain jQuery, but I would prefer to use the jQuery Validator plugin since that is how all of the other validation on the page is done.
I can group those checkboxes using jQuery by saying $('#email_lists li');, but I'm not really sure how to use something like that and tell the jQuery Validator plugin to use that as a group.
Assuming that you can give the checkboxes a class name (the jQuery needs something to work with):
<input class="validationGroupOne" name="checkbox1" type="checkbox" />
<input class="validationGroupOne" name="checkbox2" type="checkbox" />
<input class="validationGroupOne" name="checkbox3" type="checkbox" />
<input class="validationGroupOne" name="checkbox4" type="checkbox" />
You should be able to plug in the .validationGroupOne class-selector in place of the, usual, name attribute.
This was my solution :-)
Use:
<div id="list">
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
</div>
<input type="hidden" name="the_real_field_name" />
Then in jquery validate plugin block:
rules : {
chkbox: "required"
},
Then store the values as an array into a single hidden field like:
function updateInput() {
var allVals = [];
$('#list :checked').each(function() {
allVals.push($(this).val());
});
$('#the_real_field_name').val(allVals);
}
$(function() {
$('#list input').click(updateInput);
updateInput();
});