Cloning a DIV with jQuery - javascript

I have the following Javascript:
$("div.duplicate-fields:last-child").clone().find('input').each(function() {
this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+1) + ']'});
this.value = "";
this.checked = false;
}).removeClass("active").end().appendTo("#duplicate-section");
Inside a .click() function. This works fine. However I have the following HTML in the cloned area:
<div class="btn-group" data-toggle="buttons"><label class="btn btn-default button-array "><input type="checkbox" name="select-sessions[3][1]" value="">Session 1</label>
<label class="btn btn-default button-array "><input type="checkbox" name="select-sessions[3][2]" value="">Session 2</label>
<label class="btn btn-default button-array "><input type="checkbox" name="select-sessions[3][3]" value="">Session 3</label>
<label class="btn btn-default button-array "><input type="checkbox" name="select-sessions[3][4]" value="">Session 4</label>
<label class="btn btn-default button-array active"><input type="checkbox" name="select-sessions[3][5]" checked="" value="">Session 5</label>
</div>
Now, in the above jQuery I have this.checked=false; which makes any cloned checkbox unchecked. But unfortunately, The label.button-array still has the class of active, which means it still looks like it is checked.
So I modified my jQuery function be like this:
$("div.duplicate-fields:last-child").clone().find('input').each(function() {
this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+1) + ']'});
this.value = "";
this.checked = false;
}).find("label.button-array.active").each(function() {
$(this).removeClass("active");
}).end().appendTo("#duplicate-section");
Notice the new find() function added on to the first. However, It seems to completely remove all the HTML from the clone, and I end up with a few input boxes and that's about it. I cannot figure out why.
In this image you can see the first cloned area, and then after pressing the button (with the new find() function added in, as shown above):
Help me Stack Overflow, you're my only hope.

You are missing a .end().
So you were operating on the first selection (input), which means instead of appending the cloned div.duplicate-fields to #duplicate-section, you were instead appending your collection of inputs to #duplicate-section (which explains the five checkboxes)
Try replacing your second block with this
$("div.duplicate-fields:last-child").clone().find('input').each(function () {
this.name = this.name.replace(/\[(\d+)\]/, function (str, p1) { return '[' + (parseInt(p1, 10) + 1) + ']' });
this.value = "";
this.checked = false;
}).end().find("label.button-array.active").each(function () {
$(this).removeClass("active");
}).end().appendTo("#duplicate-section");
Bootply - http://www.bootply.com/bPwHVfFzK8

Try this:
$("div.duplicate-fields:last-child").clone().find('input').each(function() {
this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+1) + ']'});
this.value = "";
this.checked = false;
$(this).parent("label.button-array.active").removeClass("active");
}).removeClass("active").end().appendTo("#duplicate-section");

Since you are already looping each input element, you can try to use $.parent() to get the label, then edit its class.
Something like
$("div.duplicate-fields:last-child").clone().find('input').each(function() {
this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+1) + ']'});
this.value = "";
this.checked = false;
$(this).parent().removeClass("active");
}).end().appendTo("#duplicate-section");

Related

Jquery condition doesnt work

I must be doing some very basic mistake, because i cant get to result2, even though it checks the condition for it. it detects the counter and InpActive, but it only add up the counter once (but that should be enough to check for condition 2) nor perform the check for the test2 condition.
Edit: im presenting the full function. I want to make a mysqli query with each input, and i want to be able to add and take out each entry, preserving the query structure to be sent to the server. Its not working for some reason. In this post, im not adding the PHP part. Im only interested in making the jquery part work.
This is the jquery code:
var inpreco = ["", "", ""];
var altpreco = ["", "", ""];
var inprocess = ["", "", ""];
var altprocess = ["", "", ""];
var cpcounter8 = 0;
var cpcounter9 = 0;
$(".opcaopreco").click(function () {
SuperFun(this, "#preco", inpreco, altpreco, "altpreco2", "cpvalor",
"cpindex", "cpactivo", cpcounter9, "preco", "1 AND 5000");
});
$(".opcaopreco2").click(function () {
SuperFun(this, "#process", inprocess, altprocess, "altprocess2",
"cpvalor8", "cpindex8", "cpactivo8", cpcounter8, "process", "1 AND 11");
});
function SuperFun(element, input, inpArray, secArray, secArray2, inpValue,
secIndex, inpActive, counter, msqlip, ending) {
var inpValue = $("#" + element.id).val();
var secIndex = $("#" + element.id).data(secIndex);
var inpActive = $("#" + element.id).data(inpActive);
if (counter==0){
counter++;
$("#" + element.id + "l").addClass("activa");
$(element).data(inpActive, "primary");
inpArray[0] = (inpValue);
}else
if (inpActive=="") {
counter++;
$("#" + element.id + "l").addClass("activa");
$(element).data(inpActive, "yes");
inpArray[secIndex]=(" OR "+msqlip+" BETWEEN "+inpValue);
secArray[secIndex]=(secIndex);
}else
if (inpActive=="yes") {
counter--;
$("#" + element.id + "l").removeClass("activa");
$(element).data(inpActive, "");
inpArray[secIndex]="";
secArray[secIndex] = "";
}else
if (inpActive=="primary" && counter!==1) {
counter--;
$("#" + element.id + "l").removeClass("activa");
$(element).data(inpActive, "");
secArray2 = secArray.filter(Boolean);
inpArray[0]=$("#op" + secArray2[0]).val();
inpArray[$("#op" + secArray2[0]).data(secIndex)]="";
$("#op" + secArray2[0]).data(inpActive, "primary");
secArray[$("#op" + secArray2[0]).data(secIndex)]="";
} else
if (inpActive=="primary" && counter==1) {
counter--;
$("#" + element.id + "l").removeClass("activa");
$(element).data(inpActive, "");
inpArray[secIndex]="";
inpArray[0]=ending;
}
$(input).val(inpArray[0]+inpArray[1]+inpArray[2]);
};
This is the html code:
<input id="preco" type="text" name="preco" value='1 AND 5000'><br><br>
<input id="process" type="text" name="process" value='1 AND 11'><br><br>
<div id="op1l" class="input">
<input type="checkbox" id="op1" class="opcaopreco" value="201 AND 400" data-cpindex="1" data-cpactivo="">
<label for="op1"></label>
<span class="itext">€201 - €400</span>
</div>
<div id="op2l" class="input">
<input type="checkbox" id="op2" class="opcaopreco" value='401 AND 600' data-cpindex="2" data-cpactivo="">
<label for="op2"></label>
<span class="itext">€401 - €600</span>
</div>
<div id="op3l" class="input">
<input type="checkbox" id="op3" class="opcaopreco" value='601 AND 800' data-cpindex="3" data-cpactivo="">
<label for="op3"></label>
<span class="itext">€601 - €800</span>
</div>
<div id="op4l" class="input">
<input type="checkbox" id="op4" class="opcaopreco2" value="1 AND 1" data-cpindex8="1" data-cpactivo8="">
<label for="op4"></label>
<span class="itext">1 AND 1</span>
</div>
<div id="op5l" class="input">
<input type="checkbox" id="op5" class="opcaopreco2" value='2 AND 2' data-cpindex8="2" data-cpactivo8="">
<label for="op5"></label>
<span class="itext">2 AND 2</span>
</div>
<div id="op6l" class="input">
<input type="checkbox" id="op6" class="opcaopreco2" value='3 AND 3' data-cpindex8="3" data-cpactivo8="">
<label for="op6"></label>
<span class="itext">3 AND 3</span>
</div>
<div id="paramount">paramount</div>
You're initializing your counter to 0. It hits the if counter == 0 and wont continue to the else where you have the Test2 check
Ok let me show you much nicer solution for your problem:
https://jsfiddle.net/11jm9k7a/10/
Sorry I just couldn't work with your code so I totally reworked your logic - might be that I missed something so let me know. This solution will work on unlimited different parameter groups, as long as you put on each checkbox element 2 different attributes, first one is query before which will hold string that goes before group in your first case:
query-before="BETWEEN"
and some string to identify group of query for your first case:
query-type="opcaopreco"
there's no need for any class/id's manipulations since this is generic solution.
HTML:
<br>
<br>
<label for="process">Final Query</label>
<input id="process" type="text" name="process" value='' placeholder='1 AND 11'>
<br>
<br>
<div id="op1l" class="input">
<input type="checkbox" id="op1" query-before="BETWEEN" query-type="opcaopreco" class="opcaopreco" value="201 AND 400" data-cpindex="1" data-cpactivo="">
<label for="op1"></label>
<span class="itext">€201 - €400</span>
</div>
<div id="op2l" class="input">
<input type="checkbox" id="op2" query-before="BETWEEN" query-type="opcaopreco" class="opcaopreco" value='401 AND 600' data-cpindex="2" data-cpactivo="">
<label for="op2"></label>
<span class="itext">€401 - €600</span>
</div>
<div id="op3l" class="input">
<input type="checkbox" id="op3" query-before="BETWEEN" query-type="opcaopreco" class="opcaopreco" value='601 AND 800' data-cpindex="3" data-cpactivo="">
<label for="op3"></label>
<span class="itext">€601 - €800</span>
</div>
<div id="op4l" class="input">
<input type="checkbox" id="op4" query-before="" query-type="opcaopreco2" class="opcaopreco2" value="1 AND 1" data-cpindex8="1" data-cpactivo8="">
<label for="op4"></label>
<span class="itext">1 AND 1</span>
</div>
<div id="op5l" class="input">
<input type="checkbox" id="op5" query-before="" query-type="opcaopreco2" class="opcaopreco2" value='2 AND 2' data-cpindex8="2" data-cpactivo8="">
<label for="op5"></label>
<span class="itext">2 AND 2</span>
</div>
<div id="op6l" class="input">
<input type="checkbox" id="op6" query-before="" query-type="opcaopreco2" class="opcaopreco2" value='3 AND 3' data-cpindex8="3" data-cpactivo8="">
<label for="op6"></label>
<span class="itext">3 AND 3</span>
</div>
Javascript:
$(function() {
let query = {};
// itterate through all input elements that have query-type attribute
$('input[query-type]').each(function(value) {
query[$(this).attr('query-type')] = {
list: [],
queryBefore: $(this).attr('query-before'),
};
});
/* we first need to initialize arrays so we can get in your case:
query: {
opcaopreco: {
list: [],
queryBefore: 'BETWEEN'
},
opcaopreco2: {
list: [],
queryBefore: ''
},
}
*/
// after that attach on click even on all input elements that have query-type attribute
$('input[query-type]').on('click', function(event) {
// get query-type of $(this) - currently clicked element
let typeOfQuery = $(this).attr('query-type');
// check if this element is checked
if ($(this).is(":checked")) {
/* if it is checked, push value to object and you will get
query: {
opcaopreco: {
list: ['201 AND 400'],
queryBefore: 'BETWEEN'
},
opcaopreco2: {
list: [],
queryBefore: ''
},
}
*/
query[typeOfQuery].list.push($(this).val());
} else {
// remove - splice element from array - check index of value and remove 1 element at that index
query[typeOfQuery].list.splice(query[typeOfQuery].list.indexOf($(this).val()), 1);
}
// we also need to sort array to get remove order which people clicked
query[typeOfQuery].list.sort();
// create temporary array that will hold query
let fullQuery = [];
// loop through object keys
Object.keys(query).forEach((value, index) => {
// if there's something in array then do something otherwise don't do anything
if (query[value].list.length > 0) {
// first query join array with string ' AND ' to get ' AND ' between all values
// after that split it to get all values in correct order
let arrQuery = query[value].list.join(' AND ').split(' AND ');
// use string literal to create a string which is basically first element and last element
fullQuery.push(`${query[value].queryBefore} ${arrQuery[0]} AND ${arrQuery[arrQuery.length-1]}`);
// this is same as using + sign on each element with spaces in between like below
// fullQuery.push(query[value].queryBefore + ' '+ arrQuery[0] + ' AND '+ arrQuery[arrQuery.length-1]);
}
});
// join all query types with OR keyword
$('#process').val(fullQuery.join(' OR '));
});
});
This solution is very extendable and will work in most cases it won't cover every possible scenario and parts of it may require more work depending on your exact parameters that you need or that before part and I just join everything with 'OR', but will work very good for similar type of thing.

How to do something when radio button is going from checked to unchecked?

I am trying to create a function in Javascript that changes an attribute on a radio button (This is so that I can detect what radio button is checked) when someone clicks off/on it. Here is a jsFiddle explaining a little more of what I am looking to do. The only problem with the code in the jsFiddle is that it is in jQuery and I do not understand enough jQuery to convert it back to its pure Javascript counterpart. Here is my attempt to convert jQuery to Javascript. I could totally just copy the code and just use it but then I would not be learning anything.
I have been trying to figure this out for the last 4 ish hours and would really appreciate any help.
Thanks,
Alex
InitRadio('name');
function InitRadio(name) {
val = 0;
$.each($(':radio[name="' + name + '"]'), function() {
$(this).val(val++);
$(this).attr('chk', '0');
$(this).on("click", function(event) {
SetRadioButtonChkProperty($(this).val(), name);
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
});
});
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
}
function SetRadioButtonChkProperty(val, name) {
$.each($(':radio[name="' + name + '"]'), function() {
if ($(this).val() != val)
$(this).attr('chk', '0');
else {
if ($(this).attr('chk') == '0')
$(this).attr('chk', '1');
}
});
}
p {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type='radio' class='radio-button' name='name' id="input1">
<p id="1"></p>
<input type='radio' class='radio-button' name='name' id="input2">
<p id="2"></p>
<input type='radio' class='radio-button' name='name' id="input3">
<p id="3"></p>
My understanding is that you're partially through converting jQuery to javascript and you're having difficulty with the conversion due to lack of understanding about jQuery.
Below is my conversion with jQuery lines commented out and followed by their most direct Javascript equivalent. Keep in mind that some jQuery functions have different conversions depending on how you use them (though none of your code has this issue). Also, this code could benefit from a lot of cleanup both due to the conversion and due to issues with your own code. I've avoided doing any cleanup in favor of demonstrating the jQuery/Javascript equivalency.
InitRadio('name');
function InitRadio(name) {
val = 0;
//$.each($(':radio[name="' + name + '"]'), function() {
var radioButtons = [].slice.call(document.querySelectorAll('input[type="radio"][name="'+name+'"]'));
radioButtons.forEach(function(element,index){
//$(this).val(val++);
element.value = val++;
//$(this).attr('chk', '0');
element.setAttribute('chk','0');
//$(this).on("click", function(event) {
element.addEventListener('click',function(event){
//SetRadioButtonChkProperty($(this).val(), name);
SetRadioButtonChkProperty(element.value, name);
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
});
});
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
}
function SetRadioButtonChkProperty(val, name) {
//$.each($(':radio[name="' + name + '"]'), function() {
var radioButtons = [].slice.call(document.querySelectorAll('input[type="radio"][name="'+name+'"]'));
radioButtons.forEach(function(element,index){
//if ($(this).val() != val)
if (element.value != val)
//$(this).attr('chk', '0');
element.setAttribute('chk','0');
else {
//if ($(this).attr('chk') == '0')
if (element.getAttribute('chk') == '0')
//$(this).attr('chk', '1');
element.setAttribute('chk','1');
}
});
}
p {
display: inline;
}
<input type='radio' class='radio-button' name='name' id="input1">
<p id="1"></p>
<input type='radio' class='radio-button' name='name' id="input2">
<p id="2"></p>
<input type='radio' class='radio-button' name='name' id="input3">
<p id="3"></p>
Maybe this is what you want.
You can try it out in this Fiddle
HTML:
<div class="RadioList">
<input type="radio" class="radioBtn" value="r1" name="radio"> R1
<input type="radio" class="radioBtn" value="r2" name="radio"> R2
<input type="radio" class="radioBtn" value="r3" name="radio"> R3
<input type="radio" class="radioBtn" value="r4" name="radio"> R4
</div>
<div class="statusRadio">
<p>Checked Radio value: <b id="statusChecked">none</b></p>
</div>
jQuery:
$(document).ready(function() {
$(document).on('click', '.radioBtn', function() {
var valRadio = this.value;
$('#statusChecked').html(valRadio);
});
});
If you just want to know whether the radio button is checked, there's no need to set a custom attribute. Just look at its checked property.

How to change border color of checkboxes in Javascript

I am learning how to do form validation on various types of elements and want to do this in only Javascript. I have some checkboxes here and a Javascript function that checks if the checkboxes has at least one option selected on form submission. Basically the checkboxes should show up red if no option is selected. But I get the error:
Uncaught TypeError: Cannot set property 'borderColor' of undefined
function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;
if (!yes && !no) {
document.getElementsByClassName(".btn-group").style.borderColor = "red";
}
return ok;
}
<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input id = "yes" type="checkbox" name="box" value="yes" />
</i>Yes
</label>
<label class="btn active">
<input id = "no" type="checkbox" name="box" value="no" />No
</label>
</div>
There are a few problems there:
If you use getElementsByClassName you should use the classname without the dot.
The style property is for the element (while getElementsByClassName returns a list of the elements).
If you only set the color of the border (and not the style and the width) there will be no border.
Here is the correction:
function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;
if (!yes && !no) {
ok = false;
document.getElementsByClassName("btn-group")[0].style.border = '1px solid red';
} else {
document.getElementsByClassName("btn-group")[0].style.border = '';
}
return ok;
}
<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input id = "yes" type="checkbox" name="box" value="yes" />
Yes
</label>
<label class="btn active">
<input id = "no" type="checkbox" name="box" value="no" />No
</label>
</div>
<button onclick="validate()">Validate</button>
getElementsByClassName() Returns a collection of elements, so you need to iterate over the result to make sure you apply the style change to each element.
Furthermore, you need to use the element.setAttribute() method to change the style like so:
element.setAttribute("style","border-color: red");
Combining those two things should get you the result you want.
Edit: you don't have to use setAttribute() if you don't want to, as Neal pointed out. The important thing to take away is that you need to iterate over your collection.
Edit 2:
Looking at your code again, I noticed that when you call document.getElementsByClassName(".btn-group").style.borderColor = "red";, you're not retrieving the check boxes, you're getting a collection of divs of class btn-group, so you're actually attempting to set the border color of the div to be red, not the check boxes. You're also always returning true unconditionally at the end of validate().
If you're only checking these 2 check boxes, you can just simply use the id's to change them:
function validate() {
var ok = true;
var yes = document.getElementById("yes").checked
var no = document.getElementById("no").checked;
if (!yes && !no) {
document.getElementById("yes").setAttribute("style","border-color: red");
document.getElementById("no").setAttribute("style","border-color: red");
// no checkbox selected, validation should fail and return false
return !ok;
} else {
// checkbox selected, validation should pass and return true
return ok;
}
}
You should add or remove a class to the button group in order to hide show the border. Just add or remove the class when validation changes.
Also, you need to either iterate over all the button group classes or choose one.
Note: I used the class methods from You Might Not Need jQuery.
function validate() {
var btnGroups = document.getElementsByClassName("btn-group");
for (var i = 0; i < btnGroups.length; i++) {
var btnGroup = btnGroups[i];
var yes = document.getElementById("yes")['checked'] == true;
var no = document.getElementById("no")['checked'] == true;
if (!yes && !no) {
if (!hasClass(btnGroup, 'invalid')) addClass(btnGroup, 'invalid');
return false;
} else {
if (hasClass(btnGroup, 'invalid')) removeClass(btnGroup, 'invalid');
}
}
return true;
}
function hasClass(el, className) {
if (el.classList) return el.classList.contains(className);
else return new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
}
function addClass(el, className) {
if (el.classList) el.classList.add(className);
else el.className += ' ' + className;
}
function removeClass(el, className) {
if (el.classList) el.classList.remove(className);
else el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
.btn-group.invalid {
border : thin solid red;
}
<div data-toggle="buttons" class="btn-group">
<label class="btn active">
<input type="checkbox" id="yes" name="box" value="yes" onchange="validate()" />Yes
</label>
<label class="btn active">
<input type="checkbox" id="no" name="box" value="no" onchange="validate()" />No
</label>
</div>

get data from multiple element with the sample class using ajax

I have one of the components label with the sample class tclick
<label class="btn btn-default tclick" data-tloc="value1" data-tkey="key1" >
<label class="btn btn-default tclick" data-tloc="value2" data-tkey="key2" >
<label class="btn btn-default tclick" data-tloc="value3" data-tkey="key3" >
Whenever click on any one component of label, class "checked" will be automatically added to label :
ex:
<label class="btn btn-default tclick checked" data-tloc="value1" data-tkey="key1" >
<label class="btn btn-default tclick checked" data-tloc="value2" data-tkey="key2" >
but i want get exactly data-tloc, data-tkey when label is click ?
i like code jquery and I need one solution ?
$('label.tclick').click(function() {
$(this).addClass('checked');
var tloc = $(this).data('tloc'),
tkey = $(this).data('tkey');
console.log(tloc, tkey);
});
.checked { color: red; }
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<label class="tclick" data-tloc="value1" data-tkey="key1">Label1</label>
<label class="tclick" data-tloc="value2" data-tkey="key2">Label2</label>
<label class="tclick" data-tloc="value3" data-tkey="key3">Label3</label>
Solution:
$('label.tclick').click(function(){
var tloc = $(this).data('tloc'),
tkey = $(this).data('tkey');
$(this).addClass('checked');
console.log('Tloc:' + tloc + ', Tkey: ' + tkey);
});
After 'checked' is automatically added and you just want the data attributes on click then try on change because if click executes before the checked class is added is(':checked') may not work:
$( "label.tclick" ).on('change', function() {
if($(this).is(':checked')){
console.log($(this).data('tloc'));
console.log($(this).data('tkey'));
}
});

On label click return its radio group name

http://jsfiddle.net/Yuxfv/2/
I want to be able to click on a label, and see which radio button group it belongs to. I tried this, but it always finds the first input after li (name=left), not the one closest to the label. How do I fix that?
$('input[type=radio]:enabled + label').click(function () {
var thisGroupName = $(this).closest('ul').find('input[type=radio]:enabled').attr('name');
alert("group name: " + thisGroupName);
});
HTML
<ul>
<li>
<input type="radio" class="radio-red" name="left" id="a1">
<label for="a1">a1</label>
<input type="radio" class="radio-blue" name="right" id="a2">
<label for="a2">a2</label>
</li>
<li>
<input type="radio" class="radio-red" name="left" id="b1">
<label for="b1">b1</label>
<input type="radio" class="radio-blue" name="right" id="b2">
<label for="b2">b2</label>
</li>
<li>
<input type="radio" class="radio-red" name="left" id="b3">
<label for="b3">b3</label>
<input type="radio" class="radio-blue" name="right" id="b4">
<label for="b4">b4</label>
</li>
</ul>
Dont go to ul and come back into li. Try using prev() if you need to get the input's group :
$('input[type=radio]:enabled + label').click(function () {
var thisGroupName = $(this).prev('input[type=radio]:checked').attr('name');
alert("group name: " + thisGroupName);
});
To get more specific, you've got for attribute with you. why not use that?
$('input[type=radio]:enabled + label').click(function () {
var thisGroupName = $("#" + $(this).attr("for")).attr('name');
alert("group name: " + thisGroupName);
});
I think you need this:
$('label').click(function(){
var forRadio = $(this).attr('for');
var groupName = $('#'+forRadio).attr('name');
alert(groupName);
});
I have made a jsfiddle here
http://jsfiddle.net/psmkw/
In the code example you provided you could also look up the radio button explicitly by using the 'for' attribute of the clicked label.
$(document).ready(function () {
$('input[type=radio]:enabled + label').click(function () {
var forName = $(this).attr('for');
var thisGroupName = $('#' + forName).attr('name');
alert("group name: " + thisGroupName);
});
});
It is working in this jsFiddle:
http://jsfiddle.net/Yuxfv/4/
there is no point in traversing the DOM in that way, the label has a reference to the element. which it use to click it when you click the label.
$('input[type=radio]:enabled + label').click(function () {
var input_id = '#'+$(this).attr('for');
var group_name = $(input_id).attr('name');
alert("group name: " + group_name );
});

Categories

Resources