How to update value of a radio using Jquery - javascript

I have this HTML code for radios:
<input type='radio' name='a_27' value='Yes' id='a_27_0' />
<input type='radio' name='a_27' value='No' id='a_27_1' />
I'm trying to set the selected value of the radio using this code:
var field="a_" + this.id;
$('[name="' + field + '"]').val(this.value);
console.log("name is " + field + ", val is " + this.value);
However it doesn't work, nothing happens when this runs. Here's the output from Firebug's console which occurs after the 3rd line:
name is a_27, val is Yes
Any ideas?
I would prefer a method which would also work on <select>s, so I wouldn't need to write additional/seperate code for radios and selects.
Edit: A weird problem I've noticed that although my html code gives a different value (yes/no), in firebug it shows both radios as having the value 'yes'. If I select no and click save, the javascript function still receives 'yes' instead of no. Am I doing something wrong?
Edit 2: The full function:
function processMultiOptAnswers()
{
$.each(multiOpts,function()
{
var field="a_" + this.id;
console.log("name is " + field + ", val is " + this.value);
$('[name="' + field + '"]').val(this.value);
}
);
}

your log should be if this.value is different.
$('[name="' + field + '"]').val(this.value);
console.log("name is " + field + ", val is " + $('[name="' + field + '"]').val());
To make it selected
$('[name="' + field + '"]').attr("checked", "checked");
I haven't tested this, but you might have to remove that attribute from the other ones.

Related

Combining radio buttons and a text field

I have four radio buttons, the last being an option for "other." Clicking this radio button reveals a hidden text field so the user can explain further. This is part of a larger form that creates an email based on the options the user chose. Basically, the four radio buttons/other field need to be combined so the user's answer to that section shows up in the email, whether they pick a radio button or type in their own response. Here's my HTML:
<h1>Reason</h1>
<input type="radio" name="reason" class="reason" value="Customer requesting escalation" onclick="document.getElementById('hiddenOtherField').style.display='none'" checked>Customer requesting escalation<br>
<input type="radio" name="reason" class="reason" value="Workaround lost" onclick="document.getElementById('hiddenOtherField').style.display='none'">Workaround lost<br>
<input type="radio" name="reason" class="reason" value="Resolution overdue" onclick="document.getElementById('hiddenOtherField').style.display='none'">Resolution overdue<br>
<input type="radio" name="reason" class="reason" id="otherRadioBtn" onclick="document.getElementById('hiddenOtherField').style.display='block'">Other...<br>
<div id="hiddenOtherField" style="display: none">
<input type="text" name="reason" id="otherFreeTextField" placeholder="Please explain...">
</div><br>
I'm getting the selected value of this "Reason" section from jQuery:
$(".reason:checked").val()
But when "Other" is checked, the value of $(."reason") is "on" instead of whatever they typed. I have no idea why or how or where the word "on" comes from (it's nowhere in my code). I know I'm missing something but I don't know what. How would I make it so if the user selects the "other" radio button, whatever they type into the text field becomes the value for "reason"? I've tried a bunch of different if statements, but it's been hours and nothing is working. Please help! Thanks!
Edit - here is the Javascript code I'm using to display my values. Again, this is all a custom HTML form used to create an email based on the options the user chose. All of the other things here I'm getting the values of are working because they're straightforward.
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + $(".reason:checked").val() + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
I'm using a button at the end of my form to generate the email:
<input type="submit" value="Generate email" onclick="generateEmail()">
If you want to get the input value that the user typed you need to use :
$("#otherFreeTextField").val()
So you have to add a check if the other is checked then the reason will be the value of the input :
var reason = $(".reason:checked").val();
if( $('#otherRadioBtn').is(':checked') ) {
reason = $("#otherFreeTextField").val();
}
As a shortcut you could use :
$('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
In you context the condition should be injected like :
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var reason = $('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + reason + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
This is happening because you are checking the status of textbox if visible or not.$(".reason:checked").val(). That's why it's giving on cause it's visible.
Try: $(‘.reason:textbox’).val()

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.

Reloading Radio button value

How to reload radio button list value?
I assignedtext box value as follows,
document.getElementById('txtvalue' + id).value = document.getElementById('txtoriginalvalue' + id + '2').innerHTML;
I tried same for radio button but i can't able to reload. please help me out. Thanks.
Check out the link below.
http://jsbin.com/nohoqomuru/1/edit?html,js,output
function Cancel(){
var sId = '#'+selectedId;
$(sId).prop("checked", true);
$('#Save').attr('disabled' , true);
$('#Cancel').attr('disabled' , true);
}
radioButtonVal= document.getElementById('radiooriginalvalue' + id + '2').innerHTML;
$("input[name=radiobuttonname'" + id + "'][value=" + radioButtonVal + "]").attr('checked', 'checked');
By doing this I got output .

Radio Input gets unchecked after jQuery html operation

I'm getting an extremely weird error. My radio button gets unchecked after doing the following operations:
var $page = $('[data-shortcode-page="' + shortcode + '"]', $webrock).html();
//CHECKED
console.log($('[data-shortcode-page="' + shortcode + '"] :checked', $webrock).length)
$('.webrock-page-content', $addPage).replaceWith($page);
//UNCHECKED
console.log($('[data-shortcode-page="' + shortcode + '"] :checked', $webrock).length)
Does anyone know why this is happening? Here's a jsFiddle: http://jsfiddle.net/mVB2q/1/
Thank you very much!
You are cloning a radio group with the same name. You need to update the name of the cloned radio group. Here is a simple solution where I am hardcoding in "test1" for the new group name, but you may want to modify it to fit your needs:
var shortcode = 'object';
var $page = $('[data-shortcode-page="' + shortcode + '"]');
console.log($('[data-shortcode-page="' + shortcode + '"] :checked').length);
//after cloning the radio buttons, find radio buttons and update the name attribute.
$('.webrock-page-content').html($page.clone().find("input[type='radio']").attr("name", "test1").end().html());
console.log($('[data-shortcode-page="' + shortcode + '"] :checked').length);
Updated fiddle.

Jquery prop function is not working as expected

I am trying to enable/disable some hidden fields based on some calculation and using jquery
prop function, here is the code
function enableSelectedFieldsData(count, mapKey, index) {
$("#code_" + mapKey + "_" + index).prop("disabled", false);
$("#description_" + mapKey + "_" + index).prop("disabled", false);
$("#crossRefrence_" + mapKey + "_" + index).prop("disabled", false);
$("#image_" + mapKey + "_" + index).prop("disabled", false);
$("#price_" + mapKey + "_" + index).prop("disabled", false);
// disable all other fields
for (var i = 0; i < count; i++) {
if (i != index) {
$("#code_" + mapKey + "_" + i).prop("disabled", true);
$("#description_" + mapKey + "_" + i).prop("disabled", true);
$("#crossRefrence_" + mapKey + "_" + i).prop("disabled", true);
$("#image_" + mapKey + "_" + i).prop("disabled", true);
$("#price_" + mapKey + "_" + i).prop("disabled", true);
}
}
}
Initially i am setting disable=true for all fields and based on the selection i m trying to enable selected fields while disabling other fields, since as per my knowledge disable fields never got submitted to the server on submitting the form, but in my case they are getting submitted.
on checking using firebug i saw that the disable field value for non selected item is getting set as "" like disable=""
i am not sure where i am setting things wrong, any help or pointer in this regard will really be helpful.
Edit
I have taken out the relevant section from my generated HTML and placed it at jsfiddle
please have a look
Do you have prop() available?
prop() was added in jQuery 1.6 and is used like this:
$("input").prop('disabled', true);
$("input").prop('disabled', false);
If you are using jQuery 1.5.x or lower you can use attr() instead as seen in this FAQ - How to enable/disable form elements from the jQuery site:
// Disable #x
$('#x').attr('disabled', true);
// Enable #x
$('#x').attr('disabled', false);
// -- or --
// Disable #x
$("#x").attr('disabled', 'disabled');
// Enable #x
$("#x").removeAttr('disabled');
Assuming you are using jQuery 1.6 or higher
Your syntax looks fine.
I would guess your problem is then most likely incorrect selectors.
To validate the selector contains the element reference you expect do:
// output the selector to the console
console.log($("#code_" + mapKey + "_" + index));
If you see an element in your browser's debugging console you are looking at a valid selector, if instead you see [] the your selector is invalid.
Alternatively you can check it using the length property and alert that out:
// alert out the length of the jQuery selector
alert($("#code_" + mapKey + "_" + index).length);
If you see 0 then your selector is invalid, if you see 1 or more then your selector is correct.
The disabled attribute in HTML is a bit different to (most) other attributes, in that its presence alone is enough to disable the element.
<input type="text" name="test" disabled>
<input type="text" name="test" disabled="">
<input type="text" name="test" disabled="true">
<input type="text" name="test" disabled="false">
Those elements will all be disabled (yes, even the one with disabled="false") because the disabled attribute is present in the HTML. If you're seeing disabled="" in Firebug's HTML tab after calling
.prop('disabled', true);
then that's the correct behaviour, and the element is disabled. There's another reason why the values are still being submitted, despite being disabled.
I found that .prop("disabled", true/false) is only working on input element types (i.e. button, checkbox ect.) I was trying to call this on an anchor tag and it was not working. What I ended up doing was using .attr("disabled", true) and .removeAttr("disabled") to toggle the disabled attribute as it works on all html elements.

Categories