How to get attr value in jquery - javascript

I am trying to get value of attr " _last_val " from my input but unable to produce it.
Below is ? i have tried demo
//below is HTML
<form method="post" action="" id="feedback_form">
<input type="text" value="2014-08-11" class="date" name="add_by_datetime" _last_val="2014-08-14" >
<input type="button" name="submit_now" value="Submit" />
</form>
// below is script
jQuery(function($) {
$("form#feedback_form input[name='submit_now']").on("click",function() {
var actualadddate = $("form#feedback_form input[name='add_by_datetime']").attr('_last_val');
alert(+actualadddate+'aaaaaaaaa');
});
});
please let me know where i am wrong.
Thanks

Remove the preceded + from alert and try,
alert(actualadddate + 'aaaaaaaaa');
Live working demo
Note that, in your example you are using .date class to access the attribute if your page has more than 1 element having same class then it will not give you the accurate date. So, be carefull in that case or use unique id to get the attribute.

Remove + operator from beginning. Use:
alert(actualadddate+"aaaaaaaaa");
Demo

because of the + before actualadddate its converted to a number, that results in NaN (Not a Number)
so, remove it
alert(actualadddate+'aaaaaaaaa');
http://jsfiddle.net/59o60g7e/10/

Since, actualadddate is not a number, it thows NaN i.e. not a number. Remove + from the alert which you used to typecast.
Use this instead,
alert(actualadddate+"aaaaaaaaa");
Also, instead of using user defined attributes. Use data attribute to store your custom values.

The only thing wrong in your code is the alert call. http://jsfiddle.net/rcnw1op0/

Related

Adding button's value from array

EDIT: I want to insert value="questions[questionNum]['choices'][i]", I do not know the syntax to do this.
I wish to change the value of buttons, using values from a multi level array. It worked with radio buttons, but I would like to use standard buttons this time.
$('#showChoices').append('<input type="button" id="buttons">' + questions[questionNum]['choices'][i] + '</input>');
This works but the following doesn't:
$('#showChoices').append('<input type="button" id="buttons" value='"questions[questionNum]['choices'][i]"'></input>');
JSBin of the first
Thanks
You just want to be able to set the value prop with JavaScript? You just need to add the value with string concatenation after value, just like in your first example.
$('#showChoices').append('<input type="button" id="buttons" value=' + questions[questionNum]['choices'][i] + '></input>');
Or if you want you could try template strings:
$('#showChoices').append(`<input type="button" id="buttons" value=${questions[questionNum]['choices'][i]}></input>`);
They use backticks instead of single or double-quotes and instead of concatination (with +'s) you just write the JavaScript directly in the string, sort of like in your example — but it needs to be wrapped in ${}
Try this :
$('#showChoices').append('<input type="button" id="buttons" value="'+ questions[questionNum]['choices'][i] +'"/>');
You need to add value using string concatenation. Also, id has to be unique so I have added index of choices to your id to make them unique.
var questions = {'questionNum' : {'choices' : ['foo', 'bar'] }};
for(var i = 0; i < questions.questionNum.choices.length; ++i) {
$('#showChoices').append('<input type="button" id="buttons'+[i]+'" value="' + questions.questionNum.choices[i] +'"></input>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='showChoices'></div>
Is this what you need
$('#showChoices').append('<input type="button" id="buttons" name="buttons" value='+butVal+'></input>');
You know, after answering this question, I can't help but feel we all had tunnel vision. Maybe it doesn't really matter but I feel like if you're using jQuery you should be using the attr() method rather than string concatenation in the first place. So:
$('<input type="button" id="buttons">').attr('value', questions[questionNum]['choices'][i]).appendTo('#showChoices');
Is actually what I'd probably write. (I changed append to appendTo` to allow me to chain both properties allowing just one line.
I also noticed: the input element shouldn't be closed — it's a "self closing" tag meaning you don't add a </input> at the end.
And as you asked elsewhere: yes, for reabability's sake I would save all that code to a variable. So:
const choice = questions[questionNum]['choices'][i]; // maybe even break this down into several variables. It's quite deep
$('<input type="button" id="buttons">').attr('value', choice).appendTo('#showChoices');

Get value for CSS declaration inside HTML attribute

I am a newbie to CSS selectors and I am trying to get the value for a CSS declaration item assigned to the value attribute:
<input id="textUsername_ClientState" name="textUsername_ClientState" type="hidden" autocomplete="off" value="{"enabled":true,"emptyMessage":"","validationText":"Tom","valueAsString":"Tom","lastSetTextBoxValue":"Tom"}">
Basically I am trying to pull back one of the "Tom" values. I tried document.getElementById("textUsername_ClientState").value.style.getPropertyValue("valueAsString") but it didn't work.
Any help would be greatly appreciated.
As a newbie you have to learn a lot. You should be correct in declaring tag and its attribute
value=" { "enabled":true, "emptyMessage":"", "validationText":"Tom", "valueAsString":"Tom", "lastSetTextBoxValue":"Tom"} "
This line has some syntax error
correct form is
value='{ "enabled":"true", "emptyMessage":"", "validationText":"Tom", "valueAsString":"Tom", "lastSetTextBoxValue":"Tom"}'
Learn the difference between ' and ".
This is the format of JSON string. In this question you have to tried to access the value of valueAsString
before trying to get the value,you need to convert the json string to a javascript array by using JSON.parse() method. After parsing you can access the values individually.
I hope this helps.
Html:
<body>
<input id="textUsername_ClientState" name="textUsername_ClientState" type="hidden" autocomplete="off" value='{"enabled":"true","emptyMessage":"","validationText":"Tom","valueAsString":"Tom","lastSetTextBoxValue":"Tom"}'>
<button onclick="cool()">Cool</button>
<script>
function cool()
{
a=document.getElementById("textUsername_ClientState").value;
b=JSON.parse(a);
alert(b.valueAsString);
}
</script>
</body>

Even the most basic Javascript is failing on me - but WHY?

I'm struggling with some very basic Javascript here (not a big fan or expert in Javascript at all!), and I just cannot wrap my head around why this fails....
I have some very basic HTML markup:
Value 1: <input type="text" id="int1" /> <br />
Value 2: <input type="text" id="int2" /> <br /><br />
<input type="button" name="add" value="Add" onclick="add();" />
and then some Javascript:
<script type="text/javascript">
onerror = unhandled;
function unhandled(msg, url, line) {
alert('There was an unhandled exception');
}
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
From my (Pascal- and C#-based) understanding, the add method should read out the values from the input elements with ID's int1 and int2 and add those values and then show the result.
Seems basic and harmless enough......
But even if I do enter two valid integers (like 10 and 20) into those two textboxes, I keep getting an There was an unhandled exception and I just cannot understand what is going wrong here.
Can someone enlighten me??
$.val() returns a string value. you need to convert both returned strings to numbers and then add the values.
try this
function add() {
alert(parseFloat($('#int1').val()) + parseFloat($('#int2').val()));`
}
You have a few different issues going on here.
Firstly, if you're using jQuery, it would be best to use a click event instead of an inline function call.
Second, the values are returned as strings from the inputs, so you must convert them by using parseInt()
Also, your error handler is useless if you're not alerting the error message, the msg argument in this case.
onerror = unhandled;
function unhandled(msg, url, line) {
alert(msg);
}
$("input[name=add]").click(function() {
var int1 = parseInt($("#int1").val());
var int2 = parseInt($("#int2").val());
alert(int1 + int2);
});
Fiddle: http://jsfiddle.net/9bepJ/
Well firstly, .val() will return a string. The addition operator won't add the numeric values of those strings, it will just concatenate the strings.
But that's not causing your exception. Get rid of the everything but the add function. It should work then.
<script type="text/javascript">
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
This is, of course, assuming you included the jQuery library since that's where the $() function comes from.
Try using binding onclick event instead writing it inline.
I have made fiddle for you. Check it out
UPDATE:
http://jsfiddle.net/rkhadse_realeflow_com/FhL9g/7/
<script>
function add() {
var int1 = parseInt(document.getElementById("int1").value);
var int2 = parseInt(document.getElementById("int2").value);
alert(int1 + int2);
}
</script>
Value 1:
<input type="text" id="int1" />
<br />Value 2:
<input type="text" id="int2" />
<br />
<br />
<button onclick="add()">Add</button>
As it looks like you're using $(..) functions, be sure you're including jQuery on the page, before you use those functions.
Aside from that, I always have scope issues when I put my event handlers in HTML attributes. Try putting them in your code, which has the added benefit of being unobtrusive JavaScript (a new pattern for cleaner, more maintainable code).
Also, add an id to your button:
<input type="button" name="add" value="Add" id="myButton" />
Add event handler in code and remove onclick attribute from your button
document.getElementById('myButton').onclick = add;

Javascript select element with complicated ID

need some help! am trying to get the value of the below input id "j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" and have tried jquery and javascript such as: document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63") but keep getting a null result. ID can't be changed either, any help appreciated
<td class="sf42_cell_bottom_light"><span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61"><input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417"></span></td>
Use this:
$("[id='j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61']")
By the way, since you are apperently using JSF, this is a good practice to set id to each component to avoid such horrible ids (who can changes if you add/remove components).
See more information in this thread:
Handling colon in element ID with jQuery
Do you have any control of the element? Can you add a class to it?
var val= document.getElementsByClassName("TheClassName");
Or you can get the TD with class sf42_cell_bottom_light (if it is unique) then get its INPUT elements by:
var theTd= document.getElementsByClassName("sf42_cell_bottom_light");
var val = theTD.getElementsByTagName("INPUT");
I need to see more of the HTML to give you an better answer.
You may need to escape colon in your id .So
try this
function RemoveInvalidCharacter(myid) {
return '#' + myid.replace(/(:|\.|\[|\])/g, "\\$1");
}
And call like this
$(RemoveInvalidCharacter('j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61'));
Have a look at How do I select an element by an ID that has characters used in CSS notation
I have tested this code:
<td class="sf42_cell_bottom_light">
<span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61">
<input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417">
</span>
</td>
<script type="text/javascript">
document.write(document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63").value);
</script>
in FF, IE, Chrome (the latest versions)... and seems to work ok... ar you sure it is about this id?
Replace:
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63")
with
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63")
The id is different.
http://jsfiddle.net/wNePW/

Get escaped html from td and put it into input as value

I have html
<table>
<tr><td id="cell"><a href="">Google.com</a></td></tr>
</table>
<div id="to"></div>
And I have javascript
$(document).ready(function() {
var html = '<input type="text" value="'+$("#cell").html()+'" />'
$("#to").append(html);
});
I don't know why, but when executing this code I'm getting only <a href= in input. In firebug's inspector input html appears as <input type="text" a>="" >google.com<="" value="<a href=" > As you can see, $quot; are replaced with " - this is the problem.
I've tried using .text() instead of .html() - almost the same situation.
What is my mistake?
Thank you.
You need to encode the value (set via .val() in this case), not use it directly in a string, like this:
$(document).ready(function() {
var html = $('<input type="text" />').val($("#cell").html());
$("#to").append(html);
});
You can see it in a demo here. The problem is the &quote; gets decoded to " which is making your HTML look like this:
<input type="text" value="<a href="">Google.com</a>" />
You can see how that makes the browser a little crazy :)
Try this:
$(document).ready(function() {
$('<input type="text">').val($("#cell").html()).appendTo("#to");
});
Avoid building HTML from strings and variables, use the functions jQuery and the DOM give to you to assign values to attributes or change an element's text. It's safer this way, and IMHO it's more readable as well.
Try to write customize function to unescape the string
function unescape(html) {
return html.
replace(/&/gmi, '&').
replace(/"/gmi, '"').
replace(/>/gmi, '>').
replace(/</gmi, '<')
}

Categories

Resources