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');
Related
Struts Version: 2.3.16.3
Is there a way to populate a list of objects without having to specify the index? Currently I have to reference the collection like so:
<input name="myCollection[0].myProperty" value="some value" />
I really want to be able to do something like this:
<input name="myCollection[].myProperty" value="some value" />
I am dynamically adding and removing elements on the page with JavaScript and it has been a pain to get the indexing right with the JavaScript. Rather just have the backend add to the end of the collection in the order the elements come across from the form. Similar to how PHP processes it.
The docs for the parameters interceptor say that it is really just a ognl expression that the input name is binding to. I went to the ognl docs and it says you can reference array's like this:
array["length"]
which would be the next element in the array. The parameter interceptor is spitting out a message that it is rejecting this parameter name. I would really like to find a way to make this happen, even if it means extending the parameters interceptor.
Well, since
you are manipulating the page with Javascript
you are having troubles detecting / updating the index of elements when adding / removing them
the simplest solution is:
use the syntax you prefer when manipulating them, for example myCollection[].myProperty, and
convert them into the form desired by Struts in a pre-submit function.
This way you don't have to bother with the indexes while manipulating the elements, but only once, at the end, when you can simply loop them by name or something, and change their name with javascript by assigning the right index.
A kick-off example with jQuery:
$(function() {
$('#myform').submit(function() {
$('[name^="myCollection[]"]').each(function(index) {
var oldV = this.name;
var newV = oldV.replace("myCollection[]", "myCollection[" + index + "]");
console.log("was: " + oldV + " - now is: " + newV);
this.name = newV;
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform">
Open Javascript Console, then press submit, then inspect input elements
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<input name="myCollection[].myProperty" />
<br>
<button>submit</button>
</form>
You need somehow to identify which object some property belongs to. Indexes are simplest way to do that, so you cannot just remove them.
There are many ways to achieve what you want. Look at Andrea's answer for one possible solution using javascript.
You can also pull object properties to simple lists and later set them to object.
E.g.
private List<String> myProperty;
can be referenced in JSP w/o indexes:
<input name="myProperty" value="first value" />
<input name="myProperty" value="second value" />
Of course you if you have many properties you need to somehow sync them in JSP in such way that order and size of the properties in list is consistent for every property.
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/
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/
I have a simple input line and want to append whatever has been entered each time somebody pushes the OK button. Sounds simple so far, still I am unable to get it working
HTML:
<p>
<input name="todo" id="todo" type="text" value="Set Me To Value" size="32" maxlength="30" />
<p id="status">Ok</p>
<br>
JQuery:
$(document).ready(function(){
$('#status').on('click', function(){
var input = $('input[name=todo]').val();
$('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>').after('#status');
});
});
I also tried my luck with append or appendTo, but both times unsuccessfully.
Just in case here is the JSFiddle: http://jsfiddle.net/NRWzE/
.after() works, but you need to set it up correctly, according to documentation it should be:
.after( content [, content ] )
So the right way is:
$("#status").after('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
Try use jquery insertAfter:
$(document).ready(function () {
$('#status').on('click', function () {
var input = $('input[name=todo]').val();
$('<br><b id="taskz">' + input + '</b> - <b id="statusz">Ok</b>').insertAfter('#status');
});
});
It looks like you meant to use:
$('#status').after('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
(see after docs)
or, alternatively insertAfter:
$('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>').insertAfter('#status');
Try this:
$('#status').click(function(){
var input = $('input[name=todo]').val();
$('#status').append('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
});
There are a few things going on, but the big thing is that you need to research more how after, append and appendTo work. Here's the basic syntax difference in the methods that share a name but one has To on the end:
Newcontent.appendTo(existingElement) returns newElements.
existingElement.append(newContent) returns existingElement.
Additionally, after puts the new element as a sibling of the reference element, whereas append puts the new element as a child. This is an important difference.
So, try this script then:
var taskid = 1;
$('#valueform').on('submit', function(){
var input = $('#todo').val();
$('<br><span id="task' + taskid.toString() + '">' + input
+ '</span> - <span id="status' + taskid.toString()
+ '">Ok</span>').appendTo('#status');
taskid += 1;
$('#todo').focus().select();
return false;
});
$('#todo').focus().select();
See a Live Demo at JSFiddle
Here's the supporting HTML:
<form id="valueform">
<input name="todo" id="todo" type="text" value="Set Me To Value" size="32" maxlength="30" />
<input type="submit" value="OK" id="okbutton">
</form>
<p id="status"></p>
There are some other concerns:
I recommend you study which HTML elements are allowed within which HTML elements.
Instead of putting a <b> tag on each item, use CSS. Additionally, if there is semantic importance for the bolding, then use <strong> instead. <b> also should probably not take an id because it is a presentation tag, not a content tag. When thinking of presentation vs. semantics, one must consider screen readers or browsers that cannot render bold text--in that case, <strong> will allow them to emphasize the text in another way if needed.
Get familiar with the jQuery documentation. Careful reading of what exactly each function does, the object it works on, the parameters expected, and the values returned will enable you to get past barriers in the future without having to ask here.
It looked to me like you wanted to put the new content inside of the #status paragraph, not after it. So I wrote my script that way. If you put it after the way you wrote it, then the most recent status will be on top--but then you have non block-level content (starting with your <br>) outside of any block-level element. So you should be appending <p> elements, or you should put your content inside the existing <p>.
Note: I added a form and made the button type submit instead of button to get easy Enter-key handling. It doesn't have to be this way.
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 "e; 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, '<')
}