I have created dynamic input elements using the JavaScript below:
while(count<n-2){
if(dataArray[count+1]=='String')
var txt = "Argument:"+(count+1)+", Prefix: <input type=\"text\" name=\"prefix[]\">, Default value: <input type=\"text\" name=\"defaultval[]\" id=\"defaultval[]\"> <br>";
else if(dataArray[count+1]=='File')
var txt = "Argument:"+(count+1)+", Prefix: <input type=\"text\" name=\"prefix[]\">, Default file: <input type=\"file\" name=\"fileToUpload[]\" id=\"fileToUpload[]\"> <br>";
$("#dynamic_element").append(txt);
count++;
}
How to get values of the created inputs using jQuery?
I mean something like this inside a function:
function myFunc(){
var x0 = $('#defaultval[0]').val();
var y0= $('#fileToUpload[0]').val();
}
Square parentheses aren't valid characters for ids. Either remove them or, instead, use:
var x0 = $('input[id="defaultval[0]"]').val();
var y0 = $('input[id="fileToUpload[0]"]').val();
Working example:
var x0 = $('input[id="defaultval[0]"]').val();
var y0 = $('input[id="fileToUpload[0]"]').val();
$('#example1').text('value of "defaultval[0]": ' + x0);
$('#example2').text('value of "fileToUpload[0]": ' + y0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="defaultval[0]" name="defaultval[0]" value="0">
<input type="text" id="fileToUpload[0]" name="fileToUpload[0]" value="1">
<br>
<span id="example1"></span>
<br>
<span id="example2"></span>
Related
I want to re-generate user's input values onto textarea with specific format.
I've created input and 'select' with various 'options' inside as well as 'button' that triggers the function.
Can someone please tell me what I'm doing wrong here..?
<SCRIPT>
function myFunction() {
var finaL = document.getElementById("textArea").value;
var spacE = " | ";
var a = document.getElementById("input1").value;
var b = document.getElementById("input2").value;
var c = document.getElementById("selecT").value;
finaL = a + spacE + b + spacE + c;
}
</SCRIPT>
In your code your are getting the value of the textarea and storing it in final variable which is just a string. What you need to do is get the reference of the textarea in the final variable and then set the value.
Working Code:
function myFunction() {
var finaL = document.getElementById("textArea");
var spacE = " | ";
var a = document.getElementById("input1").value;
var b = document.getElementById("input2").value;
var c = document.getElementById("selecT").value;
finaL.value = a + spacE + b + spacE + c;
}
<label for="input1">Male</label>
<input name="input1" id="input1" /> <br>
<label for="input2">Input 3</label>
<input name="input2" id="input2" /> <br>
<label for="selecT">Input 3</label>
<select id="selecT">
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
<option value="Value 3">Value 3</option>
</select>
<br>
<button type="button" onclick="myFunction()">Copy</button>
<br>
<label>Result</label>
<textarea id="textArea"></textarea>
just update code to this
<SCRIPT>
function myFunction() {
var finaL = document.getElementById("textArea").value;
var spacE = " | ";
var a = document.getElementById("input1").value;
var b = document.getElementById("input2").value;
var c = document.getElementById("selecT").value;
document.getElementById("textArea").value = a + spacE + b + spacE + c;
}
</SCRIPT>
what i change is from this
value = a + spacE + b + spacE + c;
to this
document.getElementById("textArea").value = a + spacE + b + spacE + c;
Trying to have it so that when the user hit's submit it will show their info inputted and calculated volume/cost that's done in javascript. However the submit button isn't showing anything when clicked. Sorry for my poor english and if it's not clear. Let me know if you need anything clarified. Here's the related code:
HTML:
<form name="landscape" action="index.html" onsubmit="return validateForm()" method="post">
...
...
<h3>Type of Planter:</h3>
<input type="radio" name="inputcontrol" value="10" id="inputcontrol1" onchange="setvisible(this.value)">Square/Rectangular Cubes
<input type="radio" name="inputcontrol" value="12" id="inputcontrol2" onchange="setvisible(this.value)">Flat bottmed cylinders
<br>
<input type="radio" name="inputcontrol" value="15" id="inputcontrol3" onchange="setvisible(this.value)">1/2 Spherical
type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)">Truncated Cone
<br>
<br>
Length:<p><input type="text" size="10" id="set1" style="visibility:hidden;" ></p>
Width:<p><input type="text" size="10" id="set2"style="visibility:hidden;" ></p>
Height:<p><input type="text" size="10" id="set3"style="visibility:hidden;" ></p>
Radius:<p><input type="text" size="10" id="set4"style="visibility:hidden;" ></p>
Radius2:<p><input type="text" size="10" id="set5"style="visibility:hidden;" ></p>
<input type=submit value="Submit" onClick="buttonandchecks();">
</form>
<br>
<br>
<h2>Order Form: </h2><h2><span id="result"></span></h2>
</body>
</html>
JAVASCRIPT:
function buttonandchecks()
{
var x;
var radio_value;
var planter="";
var infooutput="";
var total=parseFloat(0);
var volume=parseFloat(0);
var length = document.getElementById("set1").value;
var width = document.getElementById("set2").value;
var height = document.getElementById("set3").value;
var radius = document.getElementById("set4").value;
var radius2 = document.getElementById("set5").value;
var inputcontrol1 = document.getElementById("inputcontrol1");
var inputcontrol2 = document.getElementById("inputcontrol2");
var inputcontrol3 = document.getElementById("inputcontrol3");
var inputcontrol4 = document.getElementById("inputcontrol4");
for(x=0;x<document.landscape.inputcontrol.length;x++)
{
if(document.landscape.inputcontrol[x].checked)
{
radio_value=document.lanscape.inputcontrol[x].value;
}
}
radio_value=parseFloat(radio_value);
if(inputcontrol1.checked)
{
volume = length * width * height;
planter = "Square/Rectangular Cubes";
}
if(inputcontrol2.checked)
{
volume = 3.14 * radius * radius * height;
planter = "Flat bottomed cylinders";
}
if(inputcontrol3.checked)
{
volume = 1/2 * (4/3* 3.14 * radius * radius * radius);
planter = "1/2 Spherical";
}
if(inputcontrol4.checked)
{
volume = 1/3*3.14*(radius*radius*radius*radius2*radius2*radius2)*height;
planter = "Truncated cone";
}
total=radio_value * volume;
infooutput=("Firstname: " + (Text1).value + " Lastname: " + (Lname).value + " \nAddress: " + (Add).value + " \nPostal Code: " + (StPrv).value + "\n\n Planter: " + planter + "\nLength: " + length + " Width: " + width + " Height: " + height + " radius: " + radius + " 2nd radius: " + radius2 + "\n Volume: " + volume + "\n Total: " + total);
document.getElementById("result").innerHTML=infooutput;
}
Any help would be greatly appreciated. Sorry if my code isn't that good, I just started learning a week ago. Thank you!
Theres a few things that need updating.
HTML
Your last input is not structured correctly.
type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)">Truncated Cone
Instead, try:
<label><input type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)" />Truncated Cone</label>
JavaScript
Things like document.landscape.inputcontrol[x].checked and (Text1).value are not valid ways to access DOM elements. Instead, try document.getElementById() or document.getElementsByName()
For example, change
for(x=0;x<document.landscape.inputcontrol.length;x++)
{
if(document.landscape.inputcontrol[x].checked)
{
radio_value=document.lanscape.inputcontrol[x].value;
}
}
To this: (notice the bracket positions and indents for readability)
checkboxes = document.getElementsByName('inputcontrol');
for(x=0;x<checkboxes.length;x++) {
if(checkboxes[x].checked) {
radio_value=checkboxes[x].value;
}
}
Finally, if your validateForm() function is going to return true, then your form will post to index.html and the page will load losing anything that happened in buttonandchecks(). Instead, you may need to have that method return false, or remove the form tag.
For some examples of those changes, you can see it working in this JS Fiddle: https://jsfiddle.net/igor_9000/qfz6dr25/2/
Hope that helps!
I have two functions - one takes a URL in a certain format (e.g. "test.com?action=query&max_results=20") and breaks it down into dynamically generated textboxes for editing. The other puts it back together along with any edits. Both functions are called by clicking a button.
The second function is unable to find the ids of the dynamically generated textboxes - they're coming back as "null". How do I get the function to recognise ids created after the page loads?
Code:
<script>
function Split()
{
//Get table body for insert
var table = document.getElementById("ValueTableBody");
//Clear table of rows
table.innerHTML = '';
//Grab URL
var URLquery = document.getElementById("oldquery").value;
//Split on ? to isolate query
var querysplit = oldquery.split("?");
//Store main url
var mainURL = document.getElementById('mainURL');
mainURL.value=querysplit[0];
//Split on & to isolate variables
var splitagain = querysplit[1].split("&");
var i = 0;
//Loop on number of variables in query
for(i = 0; i < splitagain.length; i++){
//Split on = to isolate variables and values
var splitthird = splitagain[i].split("=");
//Insert new row into table
var row = table.insertRow(i);
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '"/>';
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];
}
}
function Unsplit()
{
var mainURL = document.getElementById('mainURL').value;
var completequery = [];
var URLarray = [];
var rowCount = document.getElementById('ValueTableBody').rows.length;
for(i = 0; i <= rowCount; i++){
//Get variable of current row
var value1 = document.getElementById('query' + i).value;
//Get value of current row
var value2 = document.getElementById('queryvalue' + i).value;
if (value1) {
if (value2) {
//If both have value, then push into array
valueArray = [];
valueArray.push(value1);
valueArray.push(value2);
//Merge into one to push into next array
var newvalue = valueArray.join("=");
URLarray.push(newvalue);
}
}
}
//Join all sections of the query together
mergearray = URLarray.join("&");
//Push mainURL
completequery.push(mainURL);
//Push completed query
completequery.push(mergearray);
//Join the query together to make complete new URL
mergearray2 = completequery.join("?");
//Display new URL
var newquery = document.getElementById('newquery');
newquery.value=mergearray2;
//Output new URL to iframe
document.getElementById('webservicedisplay').src = mergearray2;
}
</script>
HTML:
<div style="float:left;">
<h1>Webservice Tester</h1>
<p><label style="font-weight:bold; display:inline-block; vertical-align:top;">Old Webservice Call:</label> <textarea cols="60" rows="4" id="oldquery"></textarea></p>
<input type="submit" name="button" id="splitbutton" onclick="Split()" value="Split!" /> <br><br>
<p><label style="font-weight:bold;">URL:</label> <input type="text" size="50" id="mainURL"></input></p><br>
<table id="ValueTable">
<thead>
<th>Variable</th>
<th>Value</th>
</thead>
<tbody id="ValueTableBody">
</tbody>
</table>
<br>
<p><input type="submit" name="button" id="unsplit" onclick="Unsplit()" value="Unsplit!" /></p> <br><br>
<p><label style="font-weight:bold; vertical-align:top;">New Webservice Call:</label> <textarea cols="60" rows="4" id="newquery"></textarea></p>
</div>
<div style="float:left; padding-left:20px;">
<p><label style="font-weight:bold;">Output:</label></p><br>
<iframe height="450" width="500" id="webservicedisplay" src="">
</iframe>
This was fixed by the author because the 'issue was actually the loop having the "<=" condition - it was looking for one more table row that didn't exist.'
I had suggested to write the JS differently as so:
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '" value="' + splitthird[0] + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '" value="' + splitthird[1] + '"/>';
And remove:
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];
I am new to javaScript. I am building a calculator here
I have stored the input values in variables so that I can eventually manipulate the results to perform calculations based on input. For now I just want all of the values to add together.
However, rather than adding, they are concatenating. I used parseInt to prevent javascript from viewing the numbers as strings, and typeOf reveals that they are numbers.
Here is my javascript:
$(document).ready(function() {
var theTerm = $("#theTerm").val();
var theRate = $("#theRate").val();
var thePrice = $("#thePrice").val();
var theTax = $("#theTax").val();
var theDown = $("#theDown").val();
var theTrade = $("#theTrade").val();
var theResult = parseInt(theTerm + theRate + thePrice + theTax + theDown + theTrade, 10);
$("#calculate").click(function(){
alert(theResult);
alert(typeof(theResult));
});
});
and the HTML:
<div id="calculator">
<span id="calculatorHeader">Monthly Payment Calculator</span>
<table style="margin:0 auto;">
<tr>
<td style="width:40px;">Term
<input id="theTerm" size="5" value="7" name="term" style="width:35px" />
</td>
<td style="width:40px;">Rate(%)
<input id="theRate" size="5" value="7" name="apr" style="width:35px" />
</td>
<td style="width:55px;">Price($)
<input id="thePrice" size="6" maxlength="7" name="price" style="width:50px" value="7" />
</td>
<td style="width:40px;">Tax(%)
<input id="theTax" size="4" maxlength="7" name="tax" style="width:35px" value="7" />
</td>
<td style="width:40px;">Down($)
<input id="theDown" size="5" maxlength="7" name="downPmt" style="width:35px" value="7" />
</td>
<td style="width:40px;">Trade($)
<input id="theTrade" size="5" maxlength="7" name="trade" style="width:35px" value="7" />
</td>
<td style="width:78px;">Est.Monthly Pmt
<input id="theResult" size="7" maxlength="7" name="result" style="width:75px" value="0" />
</td>
</tr>
</table>
<button type="button" id="calculate">Add Boxes!</button>
</div>
Change line and apply parseInt to each obj as follow
var theResult = parseInt(theTerm) + parseInt(theRate) + parseInt(thePrice) + parseInt(theTax) + parseInt(theDown) + parseInt(theTrade);
Instead of using parseInt, you can multiply number by 1. Its much faster and easier method to covert datatype.
$(document).ready(function () {
var theTerm = $("#theTerm").val() * 1;
var theRate = $("#theRate").val() * 1;
var thePrice = $("#thePrice").val() * 1;
var theTax = $("#theTax").val() * 1;
var theDown = $("#theDown").val() * 1;
var theTrade = $("#theTrade").val() * 1;
var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;
$("#calculate").click(function () {
alert(theResult);
alert(typeof (theResult));
});
});
JSFiddle: http://jsfiddle.net/RqzPk/14/
Tidy up your code a bit and avoid repetition:
DEMO
$(document).ready(function() {
$("#calculate").click(function(){
var inputs = $("input"), theResult = 0; // `inputs` is the list of all input elements
for(var i = 0;i < inputs.length; i++) // iterate over all inputs
// parse their value, in base 10, and add to the theResult
theResult += parseInt(inputs[i].value, 10);
alert(theResult); // 42
});
});
you have to use parseInt function of java script.
for ex: var theTerm = parseInt($("#theTerm").val());
demo
You're concatenating the strings with + and then you're converting that concatenated result to an int.
You want to convert to an integer before you add. Something like:
var theTerm = parseInt($("#theTerm").val(), 10);
...
var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;
I am having 2 tricky UX JQuery problems that I'm currently working on.
I am cloning a 2 form variables using JQuery. How do I index, id them so I can label them with this id.
For example if I pick 3 from the select box I should get 3 lines of form and on the left hand side of each line should begins with a number starting 1. form, 2. form, 3 form.
The second problem I have I want to validate attendant[] against confirmattendant[]. How would I do this inside a cloned HTML code.
Here is my JSFiddle
http://jsfiddle.net/tGprH/5/
Here is my HTML code:
<select name="select" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br/>
<p>Email address, Confirm Email Address</p>
#1 <input type="text" name="attendant[]"/>
<input type="text" name="confirmattendant[]"/>
<br/>
<div id="container">
</div>
Here is my JQuery
$("select").change(function() {
var select = parseInt($('#select').val() , 10);
var $clone = '<input type="text" name="attendant[]" /><input type="text" name="confirmattendant[]" /><br/>';
console.log($clone);
var html = '';
for(var i = 1;i< select ; i++){
html += $clone;
}
$('#container').empty().html(html);
}).change();
you can print the required in your for loop like..
html += '#'+(i + 1)+ ' '+$clone;
try this
$("select").change(function() {
var select = parseInt($('#select').val() , 10);
var $clone = '<input type="text" name="attendant[]" /><input type="text" name="confirmattendant[]" /><br/>';
console.log($clone);
var html = '';
for(var i = 1;i< select ; i++){
html += '#'+(i + 1)+ ' '+$clone;
}
$('#container').empty().html(html);
})
fiddle here
About the first problem : http://jsfiddle.net/tGprH/7/
$("select").change(function() {
var select = parseInt($('#select').val() , 10);
var $clone = '<input type="text" name="attendant[]" /><input type="text" name="confirmattendant[]" /><br/>';
console.log($clone);
var html = '';
for(var i = 1;i< select ; i++){
if(i >= 1)
html += '#' + (i+1) + ' ' + $clone;
else
html += $clone;
}
$('#container').empty().html(html);
}).change();
And about the comparison : http://jsfiddle.net/tGprH/8/
<button id="compare">compare</button>
$('#compare').click(function(){
var $attendantArray = $('input[name="attendant[]"]');
var $confirmattendantArray = $('input[name="confirmattendant[]"]');
for(var i = 0;i< $attendantArray.length ; i++)
{
alert((i+1) + ' attendant [' + $($attendantArray[i]).val() + ' / ' + $($confirmattendantArray[i]).val() + ']')
}
});