Data value does not change in HTML - javascript

I must have misunderstood, but I thought that the data-value of a HTML-element changes when calling the jQuery .data() function:
<div id="empty_column_0" data-name="empty_column_0" class="settings_toggle toggle-success inline-toggle" data-target="column_0" data-value="0"></div>
When I "toggle" this element, the data-value must change from 0 to 1 and vice versa.
I do this with:
$('.settings_toggle').on('toggle', function (e, active)
{
var that = $(e.target);
//Change the data value of the element
if(active) {var bool = 1;} else {var bool = 0;}
that.data('value', bool);
console.log(that.data('value'));
});
The value changes in the console but not in the HTML?
Is this how it is suppose to work?

This is by design. jQuery data() does not update the data- HTML attributes. If you wish to update the HTML attributes you'll need to use:
that.attr('data-value', bool);

You code could work, please see the link to understand the difference between .data() and .attr():
https://api.jquery.com/data/#data1
The .data() method allows us to attach data of any type to DOM
elements in a way that is safe from circular references and therefore
from memory leaks.
jQuery Data vs Attr?

Related

change background-image value dynamically

I am trying to find all the elements with a specific background-image and change it to another one.
I tried doing it with this piexce of code:
jQuery('a').each( function() {
if ( jQuery(this).css('background-image') == 'url("someurl.png")' ) {
jQuery(this).css('background-image') == 'url("anotherurl.png")';
}
});
but it didn't work...any idea how can i do it??
since this is a really small page i would rather go threw all elements in the page...
there is a way to go threw all elements in page?
Change:
jQuery(this).css('background-image') == 'url("anotherurl.png")';
to:
jQuery(this).css('background-image','url("anotherurl.png")');
Setting a property with .css()
When setting values with jQuery's css(), you'd do
jQuery(this).css('background-image', 'url("anotherurl.png"))';
It's a function, not a property that can be set with =
You need to use the setter of css() to change the property. You can also use filter() and the instance of jQuery passed in to the document ready handler to keep the $ in use. Try this:
jQuery(function($) {
$('a').filter(function() {
return $(this).css('background-image') == 'url("someurl.png")';
}).css('background-image', 'url("anotherurl.png")');
});

I want to check if `id` has no content

I want check between id that get in var span, if empty was between it put css for input but it not work. how can fix it?
var span = '#'+$('.valid').closest('.auto_box').find('span').attr('id');
if ($(span+':empty').length != 0) {
//alert('ok')
(this).closest('.auto_box').find('input').css('background-color','#000');
}
See here my full code: http://jsfiddle.net/Pjqv2/2/
You are using (this) instead of $('.valid') or whatever you meant with it. Also, you are doing this the wrong way; .find('span') returns the jQuery objects set for that span.
You don't need to get it's ID and then check on that ID again. More importantly, your code seems the need to run on multiple instances of .auto_box. For that, you need to iterate on the set found by (".valid").closest(".auto_box"), which you can do with the jQuery .each() (.each() in jQuery docs) like this:
var autoBoxes = $(".valid").closest(".auto_box");
autoBoxes.each(function(){
if ($(this).find("span").is(":empty")) {
$(this).find("input").css("background-color", "#000");
}
});
Your updated jsfiddle with this script: http://jsfiddle.net/dvir_azulay/Pjqv2/4/
Change (this) to $(span). I updated your fiddle to reflect this change.

Why are jQuery set attributes not reflected in .html()?

I am trying to set some attributes on HTML snippets. The purpose is to repopulate a form with previous inputed values. I set attributes with .attr() but after I do a .html(), I do not see my changed attributes.
I have done a basic example here http://jsfiddle.net/ejanderson4/CSYnU/
My function looks like this:
function setValue(html,value,name){
var element=$(html);
$(element).find("[name='"+name+"']").attr('value',value)
return element.html();
}
It is setting it, but for reasons unknown to me, you can't directly query the value attribute of an input element. You need to call .val() on that element to get it.
Updated your example here
parse the html string using $.parseXML and then set the attr value
var html="<div><label id='el_c5c0f78656138c39c5eb91a9bf1d3bf6'> table input 1 </label><input type='text' value='' name='table_input_1' class='select-mini' id='table_input_1' /></div>";
var value= 'xxxxxxxxxxxxx';
var name='table_input_1';
function setValue(html,value,name){
var xml = html,
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "[name='"+name+"']" );
$title.attr("value",value);
//var element=$(html);
//element.find("[name='"+name+"']").attr('value',value)
return $title.attr("value");
}
alert(setValue(html,value,name));
here is the working fiddle http://jsfiddle.net/CSYnU/4/
also this solution requires you to use jquery version 1.5.2 and higher
update
sry for overdoing it in your scenario you have to do
function setValue(html,value,name){
var element=$(html);
$(element).find("[name='"+name+"']").attr('value',value);
return $(element).find("[name='"+name+"']").attr('value');
}
here is the fiddle http://jsfiddle.net/CSYnU/5/
you are wrapping the html in $(html) then there is no need to again wrap the cached html in $
var element = $(html);
element.find ...
see here http://jsfiddle.net/CSYnU/6/
I think the short answer here is that setting an attribute on a DOM object does not necessarily change what the browser returns for innerHTML. If you want to retrieve a particular attribute, then you should just retrieve that attribute directly.
You also have an error in your code (which jQuery might be tolerating). You've already turned element into a jQuery object so you don't need to do that again with $(element).find, you can just use element.find.
function setValue(html,value,name){
var element=$(html);
element.find("[name='"+name+"']").attr('value',value)
return element.html();
}
Depend on your code, the first problem is about element variable. It doesn't denote "table_input_1" element. To get this element, you should replace by :
var element=$(html).find("[name='"+name+"']");
The second problem is in the your return statement. Since you changed the value of input element, you have to get this value by method val() or attr('value') rather than html(). The html() method is used to get the content inside tags of a element, but in this case value is a attribute, not content.
return element.attr('value'); // element.val();
Here is the complete code:
function setValue(html,value,name){
var element=$(html).find("[name='"+name+"']");
element.attr('value',value); // element.val(value);
return element.attr('value'); // element.val();
}
One reason is that the jQuery attr method gets confused between HTML attributes and DOM properties. The imlpementation of setAttribute and getAttribute was (probably still is) buggy in IE, so in general forget about HTML attributes and use DOM properties.
In most browsers, modifying the HTML attribute (say using setAttribute) will modify the related DOM property. But in many browsers, changing the DOM property will not modify the HTML attribute.
Further, some browsers will modify an element's innerHTML based on the current DOM property, others will use the HTML attribute (which might have a different value in most browsers). HTML 5 is the first attempt to standardise the behaviour of innerHTML, note that it is not a W3C standard yet and is not consistently implemented.
The best approach is to be consistent and always set DOM properties to the values you want. Expect that an element's innerHTML may be inconsistent across browsers.
Setting the current value of an input element doesn't change the initial value, which is what the value attribute is.
There is no property to change the initial value, so you can't alter the HTML code that way.
Edit:
If you want to use the elements in the page, then just make the function return a jQuery object containing the elements instead of returning HTML code:
function setValue(html, value, name){
var elements = $(html);
elements.find("[name='"+name+"']").val(value)
return elements;
}
Adding the elements to the page works the same as using a string. Example:
var html = '<div><input type="text" name="city" /></div>';
$('#SomeForm').append(setValue(html, 'York', 'city'));

Does jQuery attr allow for non standards?

I am already using id and title but i need to parse through 2 more bits...
$(this).attr("title"); $(this).attr("id");
Will $(this).attr("custom1"); work ??
yes, and BTW you can set multiple attributes at once:
$('.myselector').attr({
src: 'thefile.gif',
width: 200,
height: 300 });
Yes, and you can use it for all of the data-attributes in HTML5. Which is the preferrable way to add extra attributes.
Additionally, all data-* attributes are automatically added to jQuery's data() object for easy access
If you just want to associate (by name) some data with a DOM element, you're better off using the ".data()" method:
$(this).data('custom1', someValue);
The ".data()" API makes HTML5-style "data-foo" attributes coded into the HTML accessible:
var foo = $(this).data('foo'); // gets the "data-foo" attribute value from element
Yes it works, but it's not a good idea.
Better use .data('foo', 'bar'); if you want to store some data on an element.
Yes, and the best thing you can do is just test it.
<script>
$(document).ready(function() {
// Handler for .ready() called.
alert( "custom1 = " + $("#myField").attr("custom1") );
});
</script>
<div id="myField" custom1="My Custom Field"></div>
Now, you are breaking markup, so I would suggest storing your info in ALT tags or NAME tags to prevent that ().

Can you use jQuery's $(this) in a one-line code to modify elements?

I'm working on a placeholder function in jquery. Right now, I just want the form element to change its value to whatever its placeholder is. I tried the following code:
$('input:text').val($(this).attr('placeholder'));
But it doesn't work. After testing it a little, I realized the problem is with using $(this) in that context. How can I change this so that it will loop through all form elements and change their value to their placeholder attribute?
$('input:text').val(function() {
return $(this).attr('placeholder');
});
or:
$('input:text').attr('value', function() {
return $(this).attr('placeholder');
});
And here's a live demo.
Most of these setter jQuery functions provide a way to specify a function whose return value will be used. This is a way to make use of $(this).
$('input:text').val(function () {
return $(this).attr('placeholder');
});
jQuery val() Reference

Categories