Radio Input gets unchecked after jQuery html operation - javascript

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.

Related

Disable Drop-down list item without removing the value from FormCollection

I have a number of the following drop-down lists within this page, each with a list of selectable users. When a user is selected in one list, I don't want them to be selected in any further lists. For this reason I have written a script to disable them.
When the form is submitted, the username of each user selected in a drop-down list should be appended to the Uservalue in the Form Collection.
This works correctly without the disabling of names but when I add seat-selectinto the class description, the names are always returned in the FormCollection as empty strings.
Do you know why this is or what I can do to keep the names populating correctly in the FormCollection?
Drop-Down List:
#Html.DropDownListFor(m => m.User, Model.UserList, "Select User", new { #class = "form-control seat-select", #id = "uniqueID", #onchange = "cleanUsers(this);" })
Java Script:
function cleanUsers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) { $(".seat-select option[value='" + val + "']").attr("disabled", true); }
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
UPDATE 06/06/2016:
Apologies to bring back an old post. I have tried the advice listed below and this works to return one of the selected values. Unfortunately, In my solution I have a number of identical drop-down lists and I need to keep track of exactly which result is from which drop-down.
I have posted my new code below. The string is overwritten when each of the drop-down menus is changed so does not currently work for me.
New JavaScript:
function cleanRowers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) {
$("#SelectedUserText").val(val);
$(".seat-select option[value='" + val + "']").attr("disabled", true);
}
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
The Hidden value being updated:
#Html.HiddenFor(m => m.SelectedUserText)
I am trying to make the code as re-usable as possible so dont really want a different identifier for each of the drop-downs but it is important that I keep track of which drop-down the information is coming from.
Is there a way in which this can be done?
Disabled attribute do not put value in form submission thats why you are receiving empty string .
Here is a trick you can apply :
Put the selected value in a hidden input field onchnage function then read the hidden value on form submission instead of reading vslue of disabled dropdown.
Hope that 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 .

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>

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.

How to update value of a radio using Jquery

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.

Categories