Why is this not working with JQuery?
The property wont be checked to true so or with asnyc function... I tried everything, but it only will working if i set the attribute checked true in browser at console. Not even with outsourced async callback functions.
for (var i = 0; i < user.benutzer.length; i++)
{
var user_var = user.benutzer[i].benutzer;
user_rep = user_var.replace(/ /g, '_');
$('#div_buttongroup').append('<label for="' + user_rep + '" class="btn btn-primary" id="label_'+user_rep+'"><input type="radio" class="user_radio" id="' + user_rep + '" value="' + user_var + '" name="radio" autocomplete="off"></input>' + user_var + '</label>');
if (i === 0)
{
t = user_rep;
$('#label_'+user_rep).addClass("btn btn-primary active");
$('#'+user_rep).prop("checked",true);
}
}
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
$('#'+user_rep).attr("checked");
I think it was a JQuery bug in combination with radiobuttons. I used a selectbox and everything was working
Related
I am running a loop which is appending input fields. Now, as I am using a loop, all the attributes are similars. So, when I need to grab any one of the then I am grabbing more than one field.
How do I dynamically change the attributes according to the index, so that I can grab the correct input field ?
ebs_no = data.number_ebs;
for(i=0;i<ebs_no;i++){
$('form.ebs').append("<br>EBS"+(i+1)+"</br>");
$('form.ebs').append('<br> SNAPSHOTNO <input type="text" name="'+i+'"></br>');
$('form.ebs').append('<input type="submit" name="submit">');
$('[name='+i+']').on('submit',function(){
alert($('[name='+i+']').val());
});
}
Replace this:
alert($('[name='+i+']').val());
by this:
alert($(this).val());
The code $(this) refers to the element being treated
Your are looking for event delegation.It is used for created Dynamically DOM elements and use class instead of iterare i in the loop
ebs_no = data.number_ebs;
for (i = 0; i < ebs_no; i++) {
$('form.ebs').append("<br>EBS" + (i + 1) + "</br>");
$('form.ebs').append('<br> SNAPSHOTNO <input type="text" class="someClass" name="' + i + '"></br>');
$('form.ebs').append('<input type="submit" name="submit">');
$('[name=' + i + ']').on('submit', function () {
alert($('[name=' + i + ']').val());
});
}
$(document).on('submit', '.someClass', function () {
alert($(this).val());
});
I’ve been teaching my self JavaScript and jQuery for a few months, but I’m still getting confused with JavaScript objects and jQuery objects.
In the following example I assigned a jQuery object to the variable $target. The $target should consist of an array of two objects.
My question is why I have to wrap the value variable again into the jQuery object in .each() function ?
$('select.to_append').change(function(){
var $target = $('select.to_append');
var $form = $('#anotherForm');
$.each($target, function(key, value){
$form.append('<input name="' + $(value).attr('name') + '" type="hidden" value="' + $(value).val() + '"></input>');
});
});
The sample code I use to append values from selects which are not parts of the form being submitted;
because $target is a jQuery object, but when you iterate you will get a dom element reference in your iteration handler not a jQuery object. So if you want to access jQuery methods on that object you need to wrap the object again.
By the way to iterate over a jQuery object you can use .each() instead of jQuery.each()
$('select.to_append').change(function () {
var $target = $('select.to_append');
var $form = $('#anotherForm');
$target.each(function (index, el) {
$form.append('<input name="' + $(el).attr('name') + '" type="hidden" value="' + $(el).val() + '"></input>');
});
});
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.
Working version http://jsfiddle.net/uxBZN/
Would it be better to just replace password or text within the type (type="password") parameter of html input tag, instead of the whole html input type tag, as seen below?
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$("#security_answer").replaceWith('<input type="text" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="text" name="hnumber" value="'+hnumber+'" id="hnumber">');
} else {
$("#security_answer").replaceWith('<input type="password" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="password" name="hnumber" value="'+hnumber+'" id="hnumber">');
}
});
This needs to work with IE 7/8 and I want to retain the currently entered text.
Yes, you can do that.
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
var type = $(this).is(':checked') ? "text" : "password";
$("#security_answer").replaceWith('<input type="' + type + '" name="answer" value="'+security_answer+'" id="security_answer" />');
$("#hnumber").replaceWith('<input type="' + type + '" name="hnumber" value="'+hnumber+'" id="hnumber" />');
});
Note: Inside the handler you can use this to refer to #unhide_typing and also if you are using jQuery ver 1.7+ then it is preferrable to use on instead of live.
Replacing some properties of HTML elements with jQuery could be tricky on older versions. I recommend you to stay with .prop() function and do not replace DOM elements.
So, your code should be this:
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$('#security_answer').prop('type', 'text');
$('#hnumber').prop('type', 'text');
} else {
$('#security_answer').prop('type', 'password');
$('#hnumber').prop('type', 'password');
}
});
Yes, it's better to just replace the type for a number of reasons:
Better performance (an element isn't getting removed and then a new one getting created/inserted into the DOM)
Doesn't break the browser's built-in undo mechanism (probably not critical for this use-case, but perhaps it is in others).
Any other event handlers bound to the original input won't get removed
Just make sure you use jQuery's .prop() method rather than .attr():
http://jsfiddle.net/uxBZN/2/
I am building a form in HTML out of a javascript object that I've imported from a JSON file.
I use a recurisve algorithm to build HTML tables, and respective elements (labels, text boxes, etc.)
The fields load with the value of the current node.
The idea is to edit the values in the textboxes; which in turn updates the javascript object. When
changes have been made, the editor will send the JSON object to the server and update the file.
The puzzling question, is how do I reference the node that has been changed? I have tried several
approaches to no avail.
EDIT:
This is a basic idea of what I'm doing:
function build_tree(obj, depth) {
for (key in obj) {
if (typeof(obj[key]) == 'object') {
print(key + "<input type="text" value='" + obj[key] + "'>");
build_tree(obj[key], depth + 1);
} else
print(key + "<input type="text" value='" + obj[key] + "'>");
}
Now, how do I bind the value of obj[key] to the text boxes, so that when I change the
value it updates the Javascript object?
document.getElementById('name').changed = true;
So now the DOM element has the property 'changed'. You can also use any other value (dates, arrays, etc)
First off you need a way to individually identify the input so, i would add a data-key attribute.
function build_tree(obj, depth) {
for (key in obj) {
if (typeof(obj[key]) == 'object') {
print(key + "<input type="text" value='" + obj[key] + "' data-key= '"+key+"'>");
build_tree(obj[key], depth + 1);
} else
print(key + "<input type="text" value='" + obj[key] + "' data-key= '"+key+"'>");
}
Then i would attach a change event handler to each text input, after the tree is built.
$('input[type="text"]').on('change',function(){
var key = $(this).data('key');
obj[key] = $(this).val();
});
obj would be a global array. Hope this makes sense.
An approach I have seen many others use is a special attribute with data- prefixed.
For example:
<div id="pie" data-like-pie="true">I do like pie.</div>
Then, to find the attribute with JavaScript:
likesPie = document.getElementByID("pie").getAttribute("data-like-pie");
Or with jQuery:
likesPie = $("#pie").data("like-pie");
As you can see, jQuery's data method automatically prepends data- to the front of the attribute.
You should take a look at knockoutjs. It has an entire binding engine that updates values between html and object model automatically. So all you need to do is to send back your JSON model whenever the right values has been entered into your textboxes or whatever you use to update your values.
This will update your original model (global obj) when the generated textboxes change.
When using your print function:
print(key + "<input type="text" value='" + obj[key] + "'>");
update it to something like:
print(key + "<input type="text" value='" + obj[key] + "' data-object-key='" + key + "' >");
And in your JS, if using JQuery you want to listen to all changes on your input elements.
Add a class if necessary.
$("input[type='text']").change(function()
{
var key = $(this).data("object-key");
obj[key] = $(this).val();
});