Find elements by multiple names jQuery - javascript

I have these 4 checkboxes and I want to find them in jQuery by their names.
Is there any way to find all 4 checkboxes by their name?
<input type="checkbox" value="1" id="RangeFlexionRightSide1" name="RangeFlexionRightSide">
<input type="checkbox" value="2" id="RangeFlexionRightSide2" name="RangeFlexionRightSide">
<input type="checkbox" value="1" id="ManualFlexionRightSide1" name="ManualFlexionRightSide">
<input type="checkbox" value="2" id="ManualFlexionRightSide2" name="ManualFlexionRightSide">
I am trying these below codes but I didn't get the result:
$("input[name^='Range Manual']").length
$("input[name^='Range,Manual']").length
$("input[name^='Range'][name^='Manual']").length

Yes you could use the ending by selector $= like :
$("input:checkbox[name$='FlexionRightSide']").length
Or using start with selctor ^= like :
$("input:checkbox[name^='Range'],input:checkbox[name^='Manual']").length
NOTE : You could give them a common class, and select them easely using class selector . like :
$('.common_class').length
console.log($("input:checkbox[name$='FlexionRightSide']").length); //4
console.log($("input:checkbox[name^='Range'],input:checkbox[name^='Manual']").length); //4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="RangeFlexionRightSide1" name="RangeFlexionRightSide">
<input type="checkbox" value="2" id="RangeFlexionRightSide2" name="RangeFlexionRightSide">
<input type="checkbox" value="1" id="ManualFlexionRightSide1" name="ManualFlexionRightSide">
<input type="checkbox" value="2" id="ManualFlexionRightSide2" name="ManualFlexionRightSide">

You can do that with *= which will check if name contains value passed.
Or you can do as your way with ^= as shown below.
In jQuery selectors
[name^='Range'] - Here ^= find element whose name starts with Range.
[name$='Range'] - Here $= find element whose name ends with Range.
[name*='Range'] - Here *= find element whose name contains Range.
Find more about jQuery Selector here.
console.log($("input[name^='Range'], input[name^='Manual']").length);
console.log($("input[name*='RightSide']").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="RangeFlexionRightSide1" name="RangeFlexionRightSide">
<input type="checkbox" value="2" id="RangeFlexionRightSide2" name="RangeFlexionRightSide">
<input type="checkbox" value="1" id="ManualFlexionRightSide1" name="ManualFlexionRightSide">
<input type="checkbox" value="2" id="ManualFlexionRightSide2" name="ManualFlexionRightSide">

I guess this is what you need:
$("input[name^='Range'],input[name^='Manual']").length

Related

it needs to count the values but its doesnt work javascript

i have made a small code but he needs to count the value + a other value but its not work but he only places everything side by side. its a realy stupid question i know. I just do not see how it should be done.
You are trying to add two strings.
When you get value, notice your value is in quotes making it a string. You can parse int from string. You want to add something to handle when only 1 number is selected.
<!DOCTYPE html>
<html>
<body>
<form id="first" name="first">
<input type="radio" name="rads" value="1" />1
<input type="radio" name="rads" value="2" />2
<input type="radio" name="rads" value="3" />3
<input type="radio" name="rads" value="4" />4
</form>
<form id="second" name="second">
<input type="radio" name="rads" value="1" />1
<input type="radio" name="rads" value="2" />2
<input type="radio" name="rads" value="3" />3
<input type="radio" name="rads" value="4" />4
</form>
<span id="result"></span>
<script>
document.onclick = function hoi(){
var first = document.first.rads.value;
var second = document.second.rads.value;
var all = parseInt(first) + parseInt(second);
result.innerHTML = all;
}
</script>
</body>
</html>
The value property on a input is string, so there is string concatenation going on, convert both inputs to a number then add:
result.innerHTML = Number(first) + Number(second)
First of all, welcome to StackOverflow!
The solution to your problem is very simple: The value property returns a string, and using + on strings concatenates them. You first have to convert it to a number using parseInt(), and then add them together which would look like so:
var all = parseInt(first) + parseInt(second);

Validating if atleast one checkbox is checked or one input field is filled

I need better validation logic, where some Checkboxes and some input fields are grouped together.
The user either have to check at least one checkbox or have to fill at least one input box.
If a checkbox is checked or an input field is filled then the complete group is validated.
What will be the best possible way to validate such a situation?
e.g
<input class="checkbox" type="checkbox" name="check-deal" value="1" grouped="deal" >
<input class="checkbox" type="checkbox" name="check-deal" value="2" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="3" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="4" grouped="deal">
<input class="input-group" type="text" name="deal-name1" value="" grouped="deal">
<input class="input-group" type="text" name="deal-name2" value="" grouped="deal">
I have defined an extra attribute grouped for all input and checkboxes that should be grouped togather
but getting no idea how to validate the group as best practice.
DEMO
Point No.1 : There isn't any attribute called grouped for html as of my knowledge but I would suggest you to use data-* prefixed attribute names like data-grouped or data-anyname which is valid
Point No.2 : I rather categorized your checkboxes and textboxes into separate divs and below is how it is:
<div class="chkbox">
<input class="checkbox" type="checkbox" name="check-deal" value="1" />
<input class="checkbox" type="checkbox" name="check-deal" value="2" />
<input class="checkbox" type="checkbox" name="check-deal" value="3" />
<input class="checkbox" type="checkbox" name="check-deal" value="4" />
</div>
<div class="txtbxs">
<input class="input-group" type="text" name="deal-name1" value="" />
<input class="input-group" type="text" name="deal-name2" value="" />
</div>
<button class="btnValidate">Validate</button>
Point No.3 : Below is how you can validate using jquery
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length; //get checkbox checked length
var filledText=$(".txtbxs .input-group").val()!="";
//get bool value whether any of the text box is filled or not
if(chkLength || filledText) //check with or condition
alert('valid')
else
alert('invalid');
});
UPDATE
DEMO
As #AkshatG pointed in his answer the discrepancy was there in my answer so I've edited it and here is the updated solution.
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length;
var filledText=false; //First set it to false
$.each($(".txtbxs .input-group"),function(index,value){
if($(value).val()!="")
{
filledText=true//if it finds any value then set it to true
return;//break from $.each
}
})
if(chkLength || filledText)
alert('valid')
else
alert('invalid');
});
You first need to take count of each validations. And then check if any of the two has count greater than 0 or not. Guruprasad's answer won't work if you enter text on second textbox because it won't filter all the textboxes. You have to use filter function for this :
$("input[type='text'],textarea").filter(function() {
return $(this).val() != "";
}).length;
Here's a jsfiddle :
http://jsfiddle.net/myfLgpdv/
Hope this helps.

Find Selected Radio Button Value Based on Multiple Attribute Selection

I have 3 different Radio Buttons in a page with the following code
<input type="radio" name"1" value="1">1</input>
<input type="radio" name"2" value="2">2</input>
<input type="radio" name"3" value="3">3</input>
How can I get the value of the selected radio button with different names ?
I tried
var option = $("input[type='radio'][name='1']:checked").val();
But giving Undefined. Any Idea's ?
You need to have them be the same name, otherwise they don't work as radios (they could all be selected), and you need your html to be valid:
<input type="radio" name="1" value="1">1
<input type="radio" name="1" value="2">2
<input type="radio" name="1" value="3">3
You're missing the = when assigning the name attribute.
<input type="radio" name="1" value="1" />
<!-- ^
Also, as others have pointed out in comments, input tags are self-closing. (although it does work even with invalid html)
Demo: http://jsfiddle.net/g7RT2/
You missed "=" sign after the "name" attribute, selector doesn't match name=1 condition: <input type="radio" name"1" value="1">1</input>
http://jsfiddle.net/gLgBj/
here is a working fiddle
http://jsfiddle.net/mW7mk/
your html is not well formated, the input is self closed and name="1" not name"1"
var options = $("input[type='radio'][name='1']:checked").val();
alert("test : " + options);
worked just fine with :
<label><input type="radio" name="1" value="1" checked="checked"/>1</label>
<label><input type="radio" name="2" value="2"/>2</label>
<label><input type="radio" name="3" value="3"/>3</label>

How get the value of multiple checkboxes in javascript

I used checkbox in two items now I can get the value of the second group of checkbox.
The first group of checkbox I use:
<input name="option" type="checkbox" value="1" id="option1">option 1
<input name="option" type="checkbox" value="2" id="option2">option 2
Then
<input name="choice" type="checkbox" value="1" id="choice1">choice 1
<input name="choice" type="checkbox" value="2" id="choice2">choice 2
How can i get the value of selected checkboxes, in each group it is only allowed to select 1 checkbox.
I just need the javascript function
You want a radio button, (where only one option can be selected at a time)
<input name="option" type="radio" value="1" id="option1">option 1
<input name="option" type="radio" value="2" id="option2">option 2
Checkboxes can be grouped into arrays by appending [] to the end of their names:
<input name="option[]" type="checkbox" value="1" id="option1">option 1
<input name="option[]" type="checkbox" value="2" id="option2">option 2
This will not get the effect you want, it will instead group the checkboxes so that all input from them will result in one array. it is still possible to select multiple checkboxes with this method.
You can use this following codes to get the value of the checkbox if you are using multiple checkboxes.
$('input[name=option]:checked').val();
And retrieve the value of radio button as
document.formName.radioboxName.value;
Since you are giving same name for the radio buttons, only one value can be selected.
Katherine if you want to select a single item from both the groups then you should go for the radio other wise you can not restrict to select only one check box and unnecessary you have to write a bulk of worth less code for that.
Also you have to mention the array of check boxes. the syntax you have taken is wrong the correct one is
<input name="option[]" type="checkbox" value="1" id="option1">option 1
<input name="option[]" type="checkbox" value="2" id="option2">option 2
and for radios
<input name="option" type="radio" value="1" id="option1">option 1
<input name="option" type="radio" value="2" id="option2">option 2
With Jquery
var checked;
$("input").each(function () {
if ($(this).is(':checked'))
checked[ $(this).attr("name")] = $(this).attr("value")
})
//checked is an array/object with all your checked checkboxs
No jQuery Pure Javascript
const checkedArr = Array.from(
document.querySelectorAll(`input[name=myCheckboxGroup]:checked`)).map(node=>node.value);

How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example

Categories

Resources