Displaying multiple html text box values in an ascending order [closed] - javascript

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

Related

How do I Separate an Array Value from input to HTML

I'm getting this value from the page source (after the page finished loading), the data is coming from a back-end process that populates a hidden text input on the page. I wish to separate this data and then display it in HTML format.
This is the code from 'View Page Source'
<input name="hiddenUserStats" type="hidden" id="hiddenUserStats" value="
99.0~35.0~8.0~.0~1.0~6.0~3.0~.0~1.0~3.8~1.8~1.0~.0~16.0" />
On the value, I'm assuming that each .0~ separates the true value that I wish to separate and display. Anyone know what would be the best step to separate and display such data? Do I start with separating them in variables?
You can use split() function to separate your stats values.
var value = document.getElementById('hiddenUserStats').getAttribute('value');
var stats = value.split('~');
for (i = 0; i < stats.length; i++)
{
var div = document.createElement('div');
div.innerText = stats[i];
document.body.appendChild(div);
}
<body>
<input name="hiddenUserStats" type="hidden" id="hiddenUserStats" value="
99.0~35.0~8.0~.0~1.0~6.0~3.0~.0~1.0~3.8~1.8~1.0~.0~16.0" />
</body>
Here is another way using native array methods;
document.getElementById('hiddenUserStats')
.getAttribute('value')
.split('~')
.map(function(val, i) {
return '<div>' + i + ': '+ val + '</div>';
})
.forEach(function(el) {
document.body.innerHTML += el;
});

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

Add line break to HTML from Js loop

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \n escape character, but it didn't do anything. Any help would be appreciated.
function generateIDs()
{
var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;
}
<form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>
<p id="numbers">
</p>
\n doesn't mean much to a browser; use <br/> instead.
Example:
// snip
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id.toString() + '<br/>';
}
//snip
Note that this is going to overwrite the previous value on each iteration. You probably want this:
par.innerHTML += id.toString() + '<br/>';

Get array of values from multiple inputs using jQuery

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();
});
?

How to call on text from a textbox to set a variable in javascript

I have a bit of a predicament. I am trying to run a variable on a loop so that it can change the loop. Here is the code that I have at the present time.
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" id="Variable"><P>
</FORM>
<script type="text/javascript">
document.getElementById("Variable").value = i;
var i=5;
for (i=0;i<=5;i++)
{
document.write(" " + i);
document.write("<br />");
}
</script>
I am trying to call upon the text in the textbox from the form in order to define var i. I would also like to point out that I am no master of HTML, and if you see that I have done this all wrong, feel free to tell me that it cannot be done.
I think you mean something like this:
var count = parseInt(document.getElementById("Variable").value, 10);
var i;
for (i = 0; i < count; ++i) {
// ...do something...
}
What that does:
Looks up the element by its ID (you already had that): document.getElementById("Variable').
Retrieves the value of its value property, which is a string.
Converts the string into an number via parseInt, using decimal (as opposed to octal or hexadecimal).
Loops from zero (inclusive) to that number (exclusive).
Note that you can't use document.write after the main parse (initial load) of the page, and you probably don't want to use the value from a form field before the main parse of the page is complete, so you probably won't be doing document.write here. You might set the innerHTML of an element, something like that.
Re my "...you can't use document.write after the main parse...": Technically, you can, but you'll completely replace the page rather than just adding to it.
Re my "...and you probably don't want to use the value from a form field before the main parse...is complete...": You can, though, as long as the form field is above the script in the page markup. I did literally mean you probably don't want to, presumably you want the user to enter some value first.
Update: Here's a more complete example, with a live copy to play with:
var element, value, count, i;
element = document.getElementById("Variable");
if (!element) {
display("Element 'Variable' not found.");
}
else {
value = element.value;
count = parseInt(value, 10);
if (isNaN(count)) {
display("'" + value + "' is not numeric");
}
else {
for (i = 0; i < count; ++i) {
display("Loop " + i);
}
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
Live copy, the display function is obviously a bit of a placeholder for whatever it is you actually want to do.
I did not understand your exact question. but I guess this is your solution :
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" id="Variable">
<input type="button" value="run" onclick="renderIt()" />
<P>
</FORM>
<script type="text/javascript">
function renderIt()
{
var max = parseInt(document.getElementById("Variable").value);
for (i=0;i<=max;i++)
{
document.write(" " + i);
document.write("<br />");
}
}
</script>

Categories

Resources