Use jQuery to select all labels of radio button group - javascript

I am trying to write a function that will be called if any of the labels for a group of radio buttons are clicked. So I'd like a way to refer to all the labels of the radio button group.
From another thread (this one) I read that I could do
$('#[radio_name] label').click(function(){
...
});
where [radio_name] is the name of the group of radio buttons. In fact, I'm just trying to implement the code in the referenced thread. Unfortunately it doesn't work for me, don't know why.
Some other threads suggested you could select a specific label with $('label[for=[radio_option_id]]'), where [radio_option_id] is the id of the radio button to which the label applies. However, that only works to select a single label. I need to select all the labels in the group, which have different ids.
EDIT: here is the more complete context as requested below.
var content = "<form id='question_form' name='question_form' action=''>" + page.text;
content += "<div id='radio_options'>";
for ( var i=0; i<page.answers.length; i++ ) {
content += "<input type='radio' name='radio_option' id='radio_option_" + i.toString() + "' value='" + i.toString() + "'><label for='radio_option_" + i.toString() + "'>" + page.answers[i] + "</label><br>";
}
content += "</div>";
content += "<p><input type='submit' id='submit_button' name='submit_button' value='Submit'></p></form>";
display_loc.html( content );

Use the ATTR contains selector
$('label[for*="radio"]').click(function(){
...
});
This would work for and label that contains radio within the for attribute
Eq.
<input type="radio" name="emotion" id="radio_sad" />
<label for="radio_sad">Sad</label>
<input type="radio" name="emotion" id="radio_happy" />
<label for="radio_happy">Happy</label>
Update
For you html code you can do the following.
$('#radio_options label').click(function(){
});

It sounds to me that you just need to apply a class to your different labels and access them that way. That way you can group the labels by class.
$('label.className').click(function(){
...
});

Related

Is there a simpler way to do this script?

I'm learning and trying to put together a little bit of jquery. Admittedly I'm finding it difficult to find a good basics guide, particularly, when adding multiple actions to one page.
I read somewhere that the document listener should only be used once. I believe I'm using it twice here, but not 100% sure how to bring it into one listener.
Also because I've been hacking bits of script together, I think I'm using parts of javascript and parts of jQuery. Is this correct?
A critique of the code below [which does work] and any advice on how best to approach learning jQuery would be most helpful. Thanks.
Script 1 styles a group of 3 radio buttons depending on which one is clicked.
Script 2 appends new inputs to the bottom of a form.
var stateNo = <?php echo $HighestPlayerID; ?> + 1;
$(document).on('click', 'input', function () {
var name = $(this).attr("name");
if ($('input[name="' + name + '"]:eq(1)')[0].checked) {
$('label[name="' + name + '"]:eq(1)').addClass('nostate');
$('label[name="' + name + '"]').removeClass('selected');
}
else {
$('label[name="' + name + '"]').removeClass('nostate selected');
if ($('input[name="' + name + '"]:eq(0)')[0].checked) {
$('label[name="' + name + '"]:eq(0)').addClass('selected');
}
else {
$('label[name="' + name + '"]:eq(2)').addClass('selected');
}
}
});
$(document).on('click', 'button[name=btnbtn]', function () {
var stateName = 'state[' + stateNo + ']';
var newPlayerAppend = `` +
`<tr><td>` +
`<input type="hidden" name="state['` + stateNo + `'][PlayerID]" value="` + stateNo + `" /></td>` +
`<td><input name="` + stateName + `[Name]" value="Name"></td>` +
`<td><input name="` + stateName + `[Team]" type="radio" value="A">` +
`<td><input name="` + stateName + `[Team]" type="radio" value="">` +
`<td><input name="` + stateName + `[Team]" type="radio" value="B">` +
`</td></tr>`;
$("tbody").append(newPlayerAppend);
stateNo++;
});
HTML for the 3 radio button inputs
<td class="Choice">
<label name="state[1][Team]" class="teampick Astate ">A
<input name="state[1][Team]" type="radio" value="A" />
</label>
<label name="state[1][Team]" class="smallx nostate ">X
<input name="state[1][Team]" type="radio" value="" checked />
</label>
<label name="state[1][Team]" class="teampick Bstate">B
<input name="state[1][Team]" type="radio" value="B" />
</label>
</td>
Some of the code can be written more concisely, or more the jQuery way, but first I want to highlight an issue with your current solution:
The following would generate invalid HTML, if it were not that browsers try to solve the inconsistency:
$("tbody").append(newPlayerAppend);
A tbody element cannot have input elements as direct children. If you really want the added content to be part of the table, you need to add a row and a cell, and put the new input elements in there.
Here is the code I would suggest, that does approximately the same as your code:
$(document).on('click', 'input', function () {
$('label[name="' + $(this).attr('name') + '"]')
.removeClass('nostate selected')
.has(':checked')
.addClass(function () {
return $(this).is('.smallx') ? 'nostate' : 'selected';
});
});
$(document).on('click', 'button[name=btnbtn]', function () {
$('tbody').append($('<tr>').append($('<td>').append(
$('<input>').attr({name: `state[${stateNo}][PlayerID]`, value: stateNo, type: 'hidden'}),
$('<input>').attr({name: `state[${stateNo}][Name]`, value: 'Name'}),
$('<input>').attr({name: `state[${stateNo}][Team]`, value: 'A', type: 'radio'})
)));
stateNo++;
});
There is no issue in having two handlers. They deal with different target elements, and even if they would deal with the same elements, it would still not be a real problem: the DOM is designed to deal with multiple event handlers.
There are 2 places you are using anonymous functions. If the code block moves to a named function, the entire code becomes more maintainable. It also helps better in debugging by telling you upfront which function name the error may lie in.
Once you have named functions you will realise that you really do have 2 event listeners for click. So there isn't much benefit of moving them in one listener (or one function you may be referring to). These both event listeners attach on document object and listen to a click event.
Class names are always better when hyphenated. a-state over Astate.
If it works it is correct code, for once you asked about correctness.
It is absolutely fine to have multiple listeners but I usually prefer making everything under one roof. Consider making code as simple as possible which saves lot of time during maintenance.
you can use $(function() {}) or document.ready().
$(document).ready(function() {
$('input[type="radio"]').click(function() {
var thisa = $(this).parent();
var name = $(this).attr("name");
// Remove :selected class from the previous selected labels.
$('label[name="' + name + '"]').removeClass('selected');
// Add conditional class with tenary operator.
thisa.parent().hasClass("smallx") ? thisa.addClass('nostate') : thisa.addClass('selected');
});
$('button[name=btnbtn]').click(function() {
var stateName = 'state[' + stateNo + ']';
// Add TR and TD before appending the row to tbody
var newPlayerAppend = `<tr><td>` +
`<input type="hidden" name="state['` + stateNo + `'][PlayerID]" value="` + stateNo + `" />` +
`<input name="` + stateName + `[Name]" value="Name">` +
`<input name="` + stateName + `[Team]" type="radio" value="A"></td></tr>`;
$("tbody").append(newPlayerAppend);
stateNo++;
});
});
Hope this helps.

jQuery onclick add textbox value to div using the ID's

I am trying to add some textbox value to some other divs.
What I'd like to obtain is somthing like this:
textbox id = "text-box-name-1" ----> div id = "div-name-1"
textbox id = "text-box-name-2" ----> div id = "div-name-2"
textbox id = "text-box-name-3" ----> div id = "div-name-3"
and so on....
How can i do this? mind that the number of divs and textboxes are dynamically generated.!
Any suggestion will be really appreciated.
Thanks
EDIT
function test() {
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
for (var i = 0; i < rooms; i++) {
$("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
};
if ($('.housecontainer').find('.appendeddiv').length) {
$("#buttonaddrooms").hide();
}
};
i have already this code that allows me to create as many divs and textboxes as i type inside the textbox as value.
Now, i want be able to set, for example as div title, what the user type inside the textbox, and the only way that i've thought till now is using the id that are dynamically generated by the code that i already have.
Thanks for editing the post...
I would suggest first to add one class as an identifier to the Textbox and Div so we can attach event with the help of jQuery
$("<div class='appendeddiv targetDiv_"+ roomcounter +"'>Room-" + roomcounter + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' lang='textInput' class='targetText_"+ roomcounter +"'></div></br>").appendTo(".infoncontainer");
After that following script will do the trick :)
<script type='text/javascript>
$(function(){
$("input.textInput").on("keyup",function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
});
</script>
As per your fiddle If you want to update value mannualy onclick of any button then write this method.
<script type='text/javascript'>
function update(){
$("input.textInput").each(function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
}
</script>

how to delete a value between <input> tags?

I'm creating checkboxes using JQuery as following:
$('<input type="checkbox" ' + 'id=' + (i+1) + '>' + (i+1) + '</input><br/>')
Then later it is removed whenever the user checks the box in:
if (this.checked) {
$(this).remove();
}
However, The input box is deleted, but the number (id) stays on the page, along the <br/> Tag, so I can see the #i there on the HTML Page.
I would like to remove them as well.
So, to in order to make my question as complete as possible, here is how the HTML is laid:
<input id="1" type="checkbox">
1
<br>
Could someone please give me a clue how to remove #i and <br/> from the page?
Thanks
as stated by other answers - input don't have closing tags
You will still need to remove all id and <br />. You can find those with .next() function in jquery. You should put your id in <label> or <span>.
Then. for example:
$(this).next('label').remove();
$(this).next('br').remove();
$(this).remove();
Code can be written shorter but it's for you to see how it works.
The text in <input> text boxes is not set with a textnode (like for textareas), but with the value attribute. (Sorry for the confusion)
Yet, you want to have a checkbox. Best, create a <label> for it, instead of a text node plus a <br /> (which is not handleable with jQuery):
<div class="inputcell">
<input type="checkbox" id="check5">
<label for="check5">5</label>
</div>
With this DOM, you can easily remove the whole box by $("#check5").parent().remove(). Note that single numbers are no valid element ids.
that's because input tags don't have closing tags and remove ignores everything after the >, change this:
$('<input type="checkbox" ' + 'id=' + (i+1) + '>' + (i+1) + '</input><br/>')
to:
$('<input type="checkbox" ' + 'id=' + (i+1) + 'value="' + (i+1) +'"><label>'+ (i+1) +'</label>')
$(this).next('label').andSelf().remove();
input tags don't have closing tag, to create a checkbox you just need the following:
$('<input type="checkbox" ' + 'id=' + (i+1) + '>');
and if you want also to use a label for that checkbox, create appropriate label or any other element, because you can't put closign tag for input and a text between them

jquery with index based radio button selected value help

I have following generated code and tried to retrive the radio button value or checked from below html generated code
HTML code generated :::
<input type="radio" name="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionnaire.value" id="SetUpTest_mergedServiceSets_0__cdaQuestionnaireresponses_0__questionnaire_valueY" value="Y" class="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionInputRadio" onchange="javascript:dataModified();"/> Yes<br />
<input type="radio" name="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionnaire.value" id="SetUpTest_mergedServiceSets_0__cdaQuestionnaireresponses_0__questionnaire_valueN" value="N" class="mergedServiceSets[0].cdaQuestionnaireresponses[0].questionInputRadio" onchange="javascript:dataModified();"/> No<br />
Jquery1.6.1 used :
var questionInputRadio = $(".mergedServiceSets[" + i + "].cdaQuestionnaireresponses[" + j + "].questionInputRadio");
where i and j are passed dynamically .
or
alert("questionInputRadio===" + $(".mergedServiceSets[0].cdaQuestionnaireresponses[0].questionInputRadio").val());
Actual results ::: undefined is displaying when i see in alert box .
It never works for index based classes or ids in jquery . please help
You need to escape [, ] and . in your selector. Something like:
$(".mergedServiceSets\\[" + i + "\\]\\.cdaQuestionnaireresponses\\[" + j + "\\]\\.questionInputRadio");
Edit: I'm actually not sure if those characters are even technically valid.

Calendar Control on Dynamically created forms

I’m trying to accomplish a small task where I have one single Form ITERATED with a Date textinput which gets its Value by a Javascript DatePicker control.
My problem is, the datepicker on all these dynamically created forms only prints value on the first textbox element in the first form, how do I give it Dynamic reference to forms[x] text box element.
My form names are being generated Dynamically as form1, form2, form3, form[x], how do I reference the inner element of that particular form whose DatePicker is being clicked.
you can download the Zip file which has the datepicker & the HTML page for the Dynamic forms from here enter link description here
function addElement() {
intTextBox = intTextBox + 1;
intTextArea = intTextArea + 1;
var contentID = document.getElementById("new-field-back");
var newTBDiv = document.createElement("div");
newTBDiv.onclick=function(){ current=this; }
newTBDiv.setAttribute("id","strText"+intTextBox);
newTBDiv.innerHTML = "<br/><br/><form method='post' name='form" + intTextBox + "'><input
id='date_of_event' name='date_of_event" + intTextBox + "' class='date-pick' value=''><div
class='date-text'><a href='#' onclick=displayDatePicker('date_of_event" + intTextBox +
"');>Calendar</a></div></div><input type='submit' value='Update'><input type='button'
onclick='removeElement()' value='Remove'></form><br/><br/>";
contentID.appendChild(newTBDiv);
}
this is the correct function
if you are sending all data using one click of a button then you need to add a hidden field on the html form containing the total number of dates to be sent.
$num=$_POST['no_of_dates'];
$i;
for ($i=1;$i<=$num;$i++)
{
$_field_name="date_of_event".$i;
$_date_get=$_POST[$_field_name];
//now you can insert the $_date_get variable into the database by running a query.
}

Categories