When i did the "inspect Element" the HTML code i got is,
<domain-picker class="pull-right"
current="{"label":"AMN/GRP","value":"assf2324234"}" in-header="true" show-in-header="true">
</domain-picker>
Could anyone please let me know in jquery
how to get the value "assf2324234" of the above "domain-picker" element.
how to set with new string for the "value" attribute of the above "domain-picker" element
Following is commented to show steps
// target element
var $picker = $('domain-picker'),
// parse current attribute value string to object
current= JSON.parse( $picker.attr('current'));
// change value
current.value ='someOtherString';
// stringify object and put back as attribute value
$picker.attr('current', JSON.stringify(current));
Modify your HTML, Use single quotes for current attribute
<domain-picker class="pull-right"
current='{"label":"AMN/GRP","value":"assf2324234"}' in-header="true" show-in-header="true">
</domain-picker>
in jQuery
var json = $("domain-picker").attr("current");
json = JSON.parse(json)
var value = json.value;
Here is working demo https://jsfiddle.net/758y0fp1/1/
As #charlietfl mentioned, if you wanna use jQuery, his answer is the 1 you need, this can be done with pure Javascript too, ie.
// getting the element
var picker = document.getElementsByTagName('domain-picker')[0];
// parsing current attribute string to object
var current= JSON.parse(picker.getAttribute('current'));
// changing the value
current.value ='newString';
// stringify the object and set the attribute again like
picker.setAttribute('current', JSON.stringify(current));
You need to first get the value of attribute .attr() in jquery or getAttribute() in javascript will help. Now since the value is an invalid JSON(as per the html provided by you), convert the invalid JSON to valid and then select the value.
var obj = document.querySelector("domain-picker").getAttribute("current");
var json = obj.replace((/'/g), "\"");
var obj = JSON.parse(json)
//console log the retrieved value.
console.log("value :", obj["value"])
// set attribute now
obj["value"] = "1234567";
document.querySelector("domain-picker").setAttribute('current', JSON.stringify(obj));
<domain-picker class="pull-right"
current="{'label':'AMN/GRP','value':'assf2324234'}" in-header="true" show-in-header="true">
Hello inpsect me to see the changed attribute value.
</domain-picker>
Related
Consider that i have the following html
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
To fetch the values i use
a = $('#other_floor_plans').val()
It returns the following
"["Pool","Office","Sprinkler","Boiler"]"
If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.
How to accomplish this?
Your value is a type of string which has a correct JSON syntax. Just parse with JSON.parse into the array and use your syntax.
const value = '["Pool","Office","Sprinkler","Boiler"]';
const array = JSON.parse(value);
console.log(array[0]);
I think you need to change little bit of your code specially in markup.
changed your input markup into this <input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
then get value by jQuery
var a = $('#other_floor_plans').val(),
a = JSON.parse(a);
console.log(a[0]);
you need to use JSON.parse because you get json formate value and need to be parsed.
for my recommendation you just comma separate value like
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="Pool, Office, Sprinkler, Boiler">
then get first value by jQuery
var a = $('#other_floor_plans').val().split(",");
console.log(a[0]);
This one is much more readable and easy I guess.
You can use eval function to convert string to array and get the value.
var a = "['Pool','Office','Sprinkler','Boiler']"; // or you can also assign like this var a ='["Pool","Office","Sprinkler","Boiler"]'
var firstItem = eval(a)[0];
console.log(firstItem); //output will be "Pool"
There you doing a wrong practice when you initialize value in input box you must contain a value in different quotation symbols.
there you take " for value assign and " also for array string, that truncate your string on the second " that's why this return only [ in your value.
Try to use like this:
HTML
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
JQuery
var a = $('#other_floor_plans').val();
a = JSON.parse(a);
console.log(a);
I have value that is displayed in span tag. If i want to post the value i have to assign that value to an input. So this is the code i have written to assign value to input and trying to post that value. But when i alert the assigned value its
showing as
[object Object]
Pls check the code and correct me.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);
and i tried this also
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);
Both the above code shows
[object Object]
Because of this i am not able to post values.
That is because the value setter function on an input return the jQuery object of that input element only, it allows you to chain the event.
Try this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Read more about it here http://api.jquery.com/val/#val-value
"lower" is an object. if you want to see the text inside, you need to call lower.val().
e.g.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
jQuery supports chaining objects return.
So, whenever you do an operation on an object (except some like .val() getter, it returns object of that selector element.
So, you can do much more operations in a single statement.
In your statement,
var lower=$("#inputElement").val(value);
alert(lower);,
It is returning the object of element #lower.
You can add more operations to it.
For example:
var lower=$("#inputElement").val(value).css('color', 'red');
You want only plain value.
So, rather you should do this:
var value = $("#spanElement").text();
$("#inputElement").val(value);
var lower=$("#inputElement").val();
alert(lower);
Just do in this way..
var span_text = $("#spanElement").text(); //get span text
$("#inputElement").val(span_text); //set span text to input value
var input_value = $("#inputElement").val(); //get input value
alert(input_value); //alert input value
Hope this will help
This is because it will return a jQuery object . If you want to see the same text which is in the input you can either use .val() like answered previously or use like this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert($("#spanElement").prop('innerHTML'));
WORKING DEMO
You are getting 'Object Object' because lower is an object if you want to get the text you need to perform below actions.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Or
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Hope it helps !
This appears very simple but I cannot see why it's not working. The selector is correct however the div .faqContent is simply not being updated with the data-height attribute.
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).data('height',h);
});
I have checked that var h is correct, it is in colsole.log as correctly holding the height.
EDIT
It's absolutely not conflict, and console shows no errors.
The data function confuses a lot of people, it's not just you. :-)
data manages jQuery's internal data object for the element, not data-* attributes. data only uses data-* attributes to set initial values, and more, it guesses at what type you want those to be based on what they look like (so something that looks like a number is converted to a number; something that looks like JSON gets converted to an object). The data method never sets data-* attributes on elements, it only sets the data on its internal data object. That means the two (the internal data object and the attribute) get out of sync:
const t = $("#target");
let value;
// Getting the attribute always gets a string
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// Using `.data`, jQuery will guess that because the attribute looks like a number,
// you want it converted to a number
value = t.data("height");
console.log(`${value} (${typeof value})`); // 1 (number)
// `data` only sets the internal data object properties, not the attribute...
t.data("height", 2);
// ...so the attribute still has `"1"`
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// ...even though the data object has 2
value = t.data("height");
console.log(`${value} (${typeof value})`); // 2 (number)
<div id="target" data-height="1"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you want to actually set a data-* attribute, use attr:
$(this).attr("data-height", h);
const t = $("#target");
let value;
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// `attr` converts whatever you give it to string
t.attr("data-height", 2);
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 2 (string)
<div id="target" data-height="1"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But if you only want this information for future use, data is fine (assuming you're okay with its automatic type conversion), just don't expect to see it in the DOM inspector, because jQuery doesn't write this information to the DOM.
You will not be able to see it in the element inspector but it is there as jquery set the data attribute internally.
try console.log($(this).data('height'));
.data() is only stores the associated new value in memory(or internally). It'll not change the attribute in the DOM hence you cannot see it updated using inspector tools.
To change the attribute, you can use .attr():
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).attr('data-height',h);
});
JQuery .data() stores the value on the element itself, it won't add an attribute.
http://api.jquery.com/data/
If you want to add an attribute, use attr:
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).attr('data-height', h);
});
http://api.jquery.com/attr/
I've got several html elements that I'm appending hashes to like so:
<p class='message' data-dependencies={'#first':{'equal':'Yes'}}>
Relevant Content
</p>
so that
$(".message").first().data("dependencies")
returns
{'#first':{'equal':'Yes'}}
But as a buddy just pointed out to me, this value is a string. So naturally the filter described below has a hard time with it.
The goal of the filter is to be able to grab elements that have a specified key, in this case "#first".
$el.children().find("*").filter(function(){
var dependency_hash = $(this).data("dependencies");
if(dependency_hash != undefined && "#first" in dependency_hash){
return true
}
});
Is there a way to access the hash as passed via the data object or is there another way I can structure the data so as to accomplish the same means of being able to select elements based on the key?
If you store it as valid JSON, you can parse it, and get is content.
<p class='message' data-dependencies='{"#first":{"equal":"Yes"}}'>
Relevant Content
</p>
var json = $(".message").first().attr("data-dependencies");
// HTML5 browsers
// var json = document.querySelector(".message").dataset.dependencies;
var parsed = $.parseJSON(data);
alert(parsed["#first"].equal); // "Yes"
Or if you use jQuery's .data(), it will parse it automatically.
var parsed = $(".message").first().data("dependencies");
alert(parsed["#first"].equal); // "Yes"
Use JSON.parse. There are polyfills if you need support in older browsers.
$el.children().find("*").filter(function(){
var dependency_hash = $(this).data("dependencies");
var parsed_hash = JSON.parse(dependency_hash);
if(parsed_hash != undefined && "#first" in parsed_hash ){
return true
}
});
You probably want to serialize your data as JSON http://json.org/ and then get it back in JS.
You can use jquery's parser http://api.jquery.com/jQuery.parseJSON/
I have 3 HTML form inputs fields that is dynamically generated by a "add more" button, with naming for the fields name as fieldName, fieldName1, fieldName2, fieldName3, and so on.
Now, I'm trying to retrieve the value from this fields with JavaScript, using the script below.
var bookingForm = document.forms['formName'];
var qty = bookingForm.fieldName +'i'.value;
with the 'i' been a generated numeric number by a for loop
when I use alert(qty), it returns NaN, when I'm expecting the value for fieldName1, fieldName2, and so on.
But when I use;
var qty = bookingForm.fieldName.value
I can get the value in that field but get NaN when I try to concatenate 1,2,3, with the fieldName.
Any help will be very much appreciated.
You use brackets to access a property using a string:
var qty = bookingForm['fieldName' + i].value;
You can't use code like:
var qty = bookingForm.fieldName +'i'.value;
bookingForm.fieldName +'i' is a string. You have to change that string into a DOM element in order to access the .value parameter.
Try document.getElementsByName('fieldName'+i)[0].value