how to get an attribute from an element with jquery? - javascript

here is my example
<fieldset data-role="controlgroup" id="test">
<legend>Radio buttons, vertical controlgroup:</legend>
<input class="status" type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked">
<label for="radio-choice-1">Cat</label>
<input class="status" type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2">
<label for="radio-choice-2">Dog</label>
<input class="status" type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3">
<label for="radio-choice-3">Hamster</label>
<input class="status" type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4">
<label for="radio-choice-4">Lizard</label>
</fieldset>
$('.status').on("click", function () {
var inputs = $('#test').find('input');
$.each(inputs, function (i, v) {
console.log(v);
});
});
i would like to get the id and val() of all radio buttons, something like:
[{
id: id1,
value: value1
} {
id: id2,
value: value2
}]
...
any ideas?

To get the attribute of an element you can use .attr() like $(el).attr('class').
But to get the desired output in the above case, you can use
$('.status').on("click", function () {
var array = $('#test').find('input').map(function(idx, el){
return {id: el.id, value: el.value}
}).get();
console.log(JSON.stringify(array));
});
Demo: Fiddle

$('.status').on("click", function () {
var radioid = $(this).attr('id'); //gets the attribute ID of the clicked `.status`
radioval = $(this).val(); //gets the value of of the clicked `.status`
alert('ID = ' + radioid + ' and VALUE = ' + radioval); //see the magic
var inputs = $('#test').find('input');
$.each(inputs, function (i, v) {
console.log(v);
});
});
Use jquery attr() to get the attribute ID (and other attributes) and val() to get the value of the radio button
DEMO

Related

Select one checkbox and disable others

I am trying to select one checkbox and disable all others. The problem is I am figure out how to do the reverse. Uncheck and enable all checkboxes.
Html:
This is a dynamic list of checkboxes
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
I have tried this:
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
})
Much simpler to use not() inside event handler to target all the others.
Use the checked state of current checkbox to determine disabled state
$(':checkbox').change(function(){
// "this" is current checkbox
$(':checkbox').not(this).prop('disabled', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
Sounds like for what you are trying to achieve a radio button list may be more appropriate.
<input type="radio" name="myRadio" value="myRadio1"/>
<input type="radio" name="myRadio" value="myRadio2"/>
<input type="radio" name="myRadio" value="myRadio3"/>
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
if ($(this).is(':checked')) {
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
} else {
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "false");
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to keep values of radio elements

SOLVED:
I am using jQuery to allow a user to dynamically add fields to a form and I am requiring that they select certain yes and no values. When I clone the row I need to keep the values on input radio elements but not on the text element. I was expecting that this would do it but no luck.
How would I keep the values on the radio elements?
Also when the previous node has radios selected the cloning duplicates the selection information. I DON'T want that to happen.
HTML:
<div class="dynamic-node">
<input type="text" name="custom-name[0]" value=""/>
<hr>
<input type="radio" name="haswood[0]" value="yes"/>Yes
<input type="radio" name="haswood[0]" value="no"/>No
<hr>
<input type="radio" name="hasmetal[0]" value="yes"/>Yes
<input type="radio" name="hasmetal[0]" value="no"/>No
<hr>
<input type="radio" name="hasplastic[0]" value="yes"/>Yes
<input type="radio" name="hasplastic[0]" value="no"/>No
</div>
<div class="clone-node">Add Row</div>
JQuery:
$cloneNode = $( ".clone-node" );
$cloneNode.click(function(){
var $newNode = $(".dynamic-node:last").clone(true);
$newNode.find('input').each(function() {
var $this = $(this);
$this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));
$this.val('');
});
$newNode.insertAfter('.dynamic-node:last');
});
Solution:
Thanks to commenters below and borrowing their fresh set of eyes I resolved this by extending the code a little and making adjustment to elements based on their type and my needs:
$cloneNode = $( ".clone-node" );
$cloneNode.click(function(){
var $newNode = $(".dynamic-node:last").clone(true);
$newNode.find('input').each(function() {
var $this = $(this);
$this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));
if( $this.is('input:text') ) {
$this.val('');
}
if( $this.is('input:radio') ) {
$this.prop('checked', false);
}
});
$newNode.insertAfter('.dynamic-node:last');
});

How to make key value pair array when chekbox checked using jquery?

I have multiple checkbox, when i check a checkbox two key value pair will generate.
Like this : Object {id: "101", name: "example"}
This will generate for every checkbox checked and i want for multiple checkbox checked array. look like this :
[{id:"id1",name:"name1"},{id:"id2",name:"name2"}]
What I have done
$('.chkCompare').click(function(event) {
var value = [],
projectName = {},
span = $(this).attr('id'),
value = $('.chkCompare:checked').map(function() {
$('#span' + span).text('ADDED').css({
"color": "green"
});
projectName['id'] = $(this).attr('id');
projectName['name'] = $(this).attr('title');
return value.push(projectName);
}).get();
});
When I uncheck checkbox they will be remove from array and want to prevent check maximum 3 checkbox if >3 then show an alert box.
You can check the length property of :checked checkbox's. Based on your condition and use event.preventDefault() to cancel the default action.
$('.chkCompare').click(function(event) {
var checkedElemets = $('.chkCompare:checked');
if (checkedElemets.length > 3) {
event.preventDefault();
alert('Only 3 checkbox can be checked');
}
var values = checkedElemets.map(function() {
return {
id: this.id,
name: this.title
};
}).get();
console.log(values)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkCompare" title='t1' id='i1' />
<input type="checkbox" class="chkCompare" title='t2' id='i2'/>
<input type="checkbox" class="chkCompare" title='t3' id='i3'/>
<input type="checkbox" class="chkCompare" title='t4' id='i4'/>
<input type="checkbox" class="chkCompare" title='t5' id='i5'/>
$("input[type='checkbox']").change(function(){
var arr = {};
var count = 0;
$.each($("input[type='checkbox']:checked"), function(){
if(count++<3){
arr[this.id] =this.name;
}else{
$(this).prop('checked', false);
}
});
console.log(JSON.stringify(arr));
});

taking the id value

I want to get the id value of the content below?
<form id="mainForm" name="mainForm">
<input type="radio" id="4" name="rads" value="1" checked>
<input type="radio" id="3" name="rads" value="2" />
<input type="radio" id="2" name="rads" value="3" />
<input type="radio" id="1" name="rads" value="4" />
</form>
<span id="result"></span>
<span id="test"></span>
<script>
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
var idVal = document.getElementsById('id');
result.innerHTML = 'You selected: '+radVal;
test.innerHTML = 'You id: '+idVal;
}
</script>
You selected value: 1
You selected id: 4
You should do
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
var idVal = document.querySelector('[name="rads"]:checked').id;
result.innerHTML = 'You selected: '+radVal;
test.innerHTML = 'You id: '+idVal;
}
You need to select the checked element using document.querySelector('[name="rads"]:checked') then get the id using .id
With Jquery you can do as follow:
var selectedOption = $(':radio[name="rads"]:checked');
var id = $(selectedOption).attr('id');
var value = $(selectedOption).attr('value');
See the jsFiddle: http://jsfiddle.net/od5fot5m/
using JQuery, this should get the value of the id for the checked input $('input:checked').attr('id')
A quick jQuery example.
$(function(){ // when DOM is loaded
$('input[name="rads"]').on('click', function(){ // attaching a click event handler to the input elements with the name "rads"
if( $(this).is(':checked') ) // If the user clicked radio, is in checked state
{
$('#result').text( 'You selected: ' + $(this).val() ); // display its value
$('#test').text( 'You id: ' + $(this).attr('id') ); // display its ID attribute's name
}
});
});
Hope it will give you some ideas.
var inputs = document.getElementsByTagName('input');
var result = document.getElementById('result');
var test = document.getElementById('test');
for(i=0; i<inputs.length; i++) {
inputs[i].addEventListener("click", function(){
result.innerHTML = 'You selected: '+ this.value;
test.innerHTML = 'You id: '+ this.id;
});
}
That should work without jQuery.
Thank you everyone :)
There is a problem, Why not print the data on the screen, although it is selected? " checked "
<input type="radio" id="4" name="rads" value="1" checked>
Coming option is selected but cannot write on the screen :(

Select at least 1 checkbox in a loop of checkboxes group

I'm trying to get this thing work for a while but I guess I need to tweak the code from somewhere. I thought, someone here could better guide me instead of banging my head to my coding screen :)
here's the actual process:
<input type="hidden" name='oneSelectionChk_1'>
<input type="checkbox" name='awp_group_1' id='id1'>
<input type="checkbox" name='awp_group_1' id='id2'>
<input type="checkbox" name='awp_group_1' id='id3'>
<input type="checkbox" name='awp_group_1' id='id4'>
<input type="hidden" name='oneSelectionChk_2'>
<input type="checkbox" name='awp_group_2' id='id5'>
<input type="checkbox" name='awp_group_2' id='id6'>
<input type="checkbox" name='awp_group_2' id='id7'>
<input type="checkbox" name='awp_group_2' id='id8'>
<input type="hidden" name='oneSelectionChk_3'>
<input type="checkbox" name='awp_group_3' id='id9'>
<input type="checkbox" name='awp_group_3' id='id10'>
<input type="checkbox" name='awp_group_3' id='id11'>
<input type="checkbox" name='awp_group_3' id='id12'>
what I'm using for jQuery is:
var chkFields = $("input[name='oneSelectionChk']");
$.each(chkFields, function(i, field){
var groupID = field.id.split('_'); // Getting the ID of the group
var chkGroupBoxes = $('input[name="awp_group_"'+groupID[1]);
if(field.value==1)
{
//$.each(chkGroupBoxes, function(j, thisChkBox){
//alert(thisChkBox.value + " #"+j);
alert( $('input[name="awp_group_"'+groupID[1]).filter(':checked').length);
if($('input[name="awp_group_"'+groupID[1]+':checked').length > 0 )
{
//$.scrollTo( '#awp_container', 1200 );
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Selected ");
//alert( "Class AlertMsgText Should be removed Now");
$("#selectInstruction_"+groupID[1]).removeClass("AlertMsgText");
//return
}
else
{
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Still not selected ");
//alert("Please select atleat 1 from Option #"+groupID[1]);
$("#selectInstruction_"+groupID[1]).addClass("AlertMsgText");
$.scrollTo( '#awp_container', 1200 );
//return;
}
//});
}
});
This code always giving me 0 length of checkboxes, I'm not sure if I need to loop through again for each checkbox or this might work?
Any quick help should be appreciated!
Try
var chkFields = $('input[name^="oneSelectionChk"]');
$.each(chkFields, function (i, field) {
var groupID = field.name.replace('oneSelectionChk_', '')
var chkGroupBoxes = $('input[name="awp_group_' + groupID + '"]');
if (chkGroupBoxes.filter(':checked').length == 0) {
alert('please select at least one checkbox under: ' + field.name)
}
});
Demo: Fiddle
There is no element with name attribute of oneSelectionChk in your markup, the hidden inputs have name attributes that start with oneSelectionChk, you have to use attribute starts with selector.
In case that elements are siblings you can select the target elements using .nextUntil() method:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]');
$hidden.each(function(){
var $chekboxes = $(this).nextUntil('input[type=hidden]'),
$checked = $checkboxes.filter(':checked'),
$unchecked = $chekboxes.not($checked);
});
Using name attributes:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]'),
$checkboxes = $('input[type=checkbox]');
$hidden.each(function() {
var n = this.name.split('_')[1];
var $grp = $checkboxes.filter('[name="awp_group_'+ n +'"]');
// ..
});

Categories