Currently using javascript to create a dynamic form for image url's, but I can't seem to figure out how to escape the javascript var the right way. The problem is with the th:field="*{imageUrl['+iterator+']}"
Code:
<script type="text/javascript" th:inline="javascript">
var info = 1;
var iterator = 0;
function add_fields() {
info++;
iterator++;
var objTo = document.getElementsByClassName('form-group')[0]
console.log(objTo);
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="form-group"><label class="col-lg-3 control-label">Field'+info+' </label><div class="col-lg-9"> <input type="text" th:field="*{imageUrl['+iterator+']}" class="form-control" name="field1" /></div></div>';
objTo.appendChild(divtest)
}
</script>
But i'll get the following error:
java.lang.NumberFormatException: For input string: "'+iterator+'"
Thanks in advance
well, looks weird cause its a java error and you have javascript code.
But try to call method toString on your number.
var nbr = 10;
var foo = 'your text' + nbr.toString() + ' more text';
I just created a javascript function which makes a input form visible and putted the thymeleaf variables in the hidden input forms
Related
Hi I'm just new to Javascript and I am trying to assign a value to a variable coming from the input box then access that variable in a loop. I have tried using document.getElementbyID('inputboxID').value; and document.getElementbyName('inputboxName').value; but it didn't work.
Here's my code:
<script>
var count = 0;
$(function(){
$('p#add_field').click(function() {
var num = document.getElementById('enfonum').value;
while (count < num) {
count +=1;
$('#container').append(
'<strong>Enforcer #'+count+'</strong><br/>'
+'<input id="field_ '+count+'"name="field[]'+'"type="text"/><br/>');
}
});
});
}
</script>
Here's the code for the input box:
<input type="text" id="enfonum" name="enfotxt"/>
and here's the code for the link that will trigger the script to be executed:
<p id="add_field">< a href="#"><span>» Add Enforcer</span></a></p>
You have to get value of enfonum input at run-time, not storing it at num var during initial page loading.
Here is the working sample with correct code:
var count = 0;
var num = document.getElementById('enfonum');
$('p#add_field').click(function () {
while (count < num.value) {
count += 1;
$('#container').append('<p><strong>Enforcer #' + count + '</strong><br/>'
+ '<input id="field_' + count + '" name="field[]' + ' "type="text"/><br/></p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="text" id="enfonum" name="enfotxt" /></p>
<p id="add_field"><span>» Add Enforcer</span></p>
<div id="container"></div>
The reason your code is not working, is simply that document.GetElementById does not exists, the correct syntax is document.getElementById.
Here's a jsfiddle with an example.
Good luck and good continuation,
Cheers !
Remove the extra } in the code, it will give you syntax error.
Tried it afterwards,the code works.
Syntax errors can break your javascript, it is wise to use plugins like firebug for firefox to fish out javascript errors.
Let me know if it works.
I have a form where you can generate automatically additional form boxes and send them to be handeled at PHP-script. How ever as I am quite lousy with Javascript and I am running in the following problem.
When the form is filled out I can see everything is filled out on the URL, except the the boxes created with JS (every box has unique name!). My guess is that the JS generated field drop out of the form tags, but can not figure out how to fix this. I would appreciate if someone could give me pointers or tell me how to fix this. I shortened the code for clarity (if something got left out please tell me). If someone is wondering why I am not using the form action. It´s because drupal tries to forward the site to wrong place if I do (surprise, not too good with drupal either :D)
<?php
require_once('customer.php');
?>
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "<div class='product'><tr><td>Sku/ID: "+intTextBox+": <input type='text' name='sku_" + intTextBox + "'/></div>";
contentID.appendChild(newTBDiv);
}
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
<table>
<form name="activate">
<div class='cu'>
<tr><td>Sku/ID (oma): <input type="text" name="sku"></td>
<td><p><a href="javascript:addElement();" >Add product</a>
<a href="javascript:removeElement();" >Remove product</a></p></td></tr>
<div id="content"></div>
</div>
<tr> <td><input type="submit" value="Submit"></td> </tr>
</form>
Customer.php
<?php
if(isset($_GET["sku_1"]))
{
echo "found it";
}
else
echo "did not find it";
?>
Any help would be much appreciated!
You could dynamically change the url of the form tag to include textbox values:
var textboxes = document.getElementsByTagName("input");
for (var i = 0; i < textboxes.length; i++){
var data = "?";
if (textboxes[i].type == "text") {
data += (data == "?" ? "" : "&") + textboxes[i].name + "=" + textboxes[i].value;
}
}
form.action += data;
I haven't tested this, you might have to dynamically add all elements
[UPDATE]
If you have trouble with the form you can try using an absolute path, if you aren't already.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model
I understand how to dynamically load HTML, I am having trouble understanding how I load it, assign, and keep track of IDs for elements inside the loaded div.
This is my main block
<div id="add-equip-container">
<div id="add-equip-content">
</div>
<button id="add-equipment">Add More Equipment</button>
<button id="submit-equipment">Submit Equipment</button>
</div>
Now, every time add-equipment is clicked, I want to load the following block into add-equip-content.
<div class="add-equip-form">
<input id="?" type="text" placeholder="Equipment Description..."/></br>
<input id="?" type="text" placeholder="Equipment Number"/></br>
<input id="?" type="text" placeholder="Other Stuff..."/></br>
</div>
Each block would be inserted beneath the previous one loaded. I have no idea how to assign and keep track of the various IDs that will be dished out during this operation. I would love a solution that does not involve jQuery. I am trying to lean vanilla JavaScript before I get into frameworks.
I am sure there may be a question or blog or something on this already, but I just don't know the best keywords to search for. Any time I use "Dynamically Load HTML" in the search keywords, all I get is AJAX Tutorial results.
Thanks in advance for any help!
One solution would be not actually load the HTML, but to create it via Javascript. This would be useful in your case as you are adding the same code to the page, only with different ID's. I would write a function like this:
var form_index = 0;
//elem is the element you are appending to.
function addForm(elem) {
//create the container
var form_container = document.createElement("div");
form_container.className = "add-equip-form";
//description input
var desc = document.createElement('input');
desc.id = "equip-desc-" + form_index;
desc.type = "text";
desc.placeholder = "Equipment Description...";
//Equipment number input
var num = document.createElement('input');
num.id = "equip-num-" + form_index;
num.type = "text";
num.placeholder = "Equipment Number";
//Other
var other = document.createElement('input');
other.id = "equip-other-" + form_index;
other.type = "text";
desc.placeholder = "Other Stuff...";
//append inputs
form_container.appendChild(desc);
form_container.appendChild(num);
form_container.appendChild(other);
//append form
elem.appendChild(form_container);
form_index++;
}
Then, to access your created ID's, all you need to know is the index of the containing div within your parent elem. See here for a javascript solution. Once you have the index, getting the form data is as easy as using your index to query based on ID's.
This should do it. You may or may not need to do the elements.push(content) if you don't need to refer back to these elements in an array. Could just iterate a counter instead.
var add_equip_content = document.getElementById('add-equip-content'),
add_equip_btn = document.getElementById('add-equipment'),
elements = [];
add_equip_btn.addEventListener('click', addEquipment, true);
function addEquipment(event){
var content = document.createElement('div'),
html = '';
content.className = 'add-equip-form';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Description..."/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Number"/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Other Stuff..."/></br>';
content.innerHTML = html;
add_equip_content.appendChild(content);
elements.push(content);
}
Can someone please let me know how to get values from several input fields?
I have a list with several inputs like this:
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
I have a solution in Javascript (on form submit):
...
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
}
How do I do the same thing in JQuery?
It's not valid to have two inputs of the same name. If you want to do this, you can use <input name="titles[]">
You can try this:
<input name="titles[]">
<input name="titles[]">
<button>submit</button>
With this jQuery
// click handler
function onClick(event) {
var titles = $('input[name^=titles]').map(function(idx, elem) {
return $(elem).val();
}).get();
console.log(titles);
event.preventDefault();
}
// attach button click listener on dom ready
$(function() {
$('button').click(onClick);
});
See it working here on jsFiddle
EDIT
This answer gives you the titles in an array instead of a string using a | separator. Personally, I think this is a lot more usable.
If you're just submitting the form and you want to support multiple values, use the .serialize method as described in the other answer
Use jQuery's native serialize function:
var data = $('input[name="additionaltitlename"]').serialize();
docs
The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.
It is very easy in jquery. you can do this as:
types = [];
$("input[name='additionaltitlename']").each(function() {
types.push($(this).val());
});
console.log(types);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="additionaltitlename1" name="additionaltitlename" class="form-control" value="abc">
<input type="text" id="additionaltitlename2" name="additionaltitlename" class="form-control" value="xyz">
In addition to #gdoron's or #macek's answer which are probably the way to go, I'd like to add that all that is wrong with the code you have posted is that you have one } too much. This works (although it still has room for improvement):
$('#getpreviewbutton').click(function(){
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
});
See: http://jsfiddle.net/8XJcc/
I don't know which browser you are using but using sth like Firebug or the Chrome Dev Tools can be pretty handy to spot simple mistakes like this. See this reference for Chrome or this one for Firefox. Even IE has one - just press F12.
Means:
str = '';
$("input[type='text']").each(function() {
str = str + '|' + $(this).val();
});
or
str = '';
$("input[name='additionaltitlename']").each(function() {
str = str + '|' + $(this).val();
});
?