for loop not working in JavaScript while Second Attempt - javascript

I got stuck in a very strange problem need help.
Actually i am trying to assign some value to dynamically generated input fields. So i tried the following code snippet. I mean to say in first step i only need to assign value for first 10 IDs and then again if assigning some other values to rest of IDs then it fails
JavaScript
<script type="text/javascript">
function callAssignMark() {
var rightMarkVal = $("#rightMarkVal").val();
var wrongMarkVal = $("#wrongMarkVal").val();
var initial= $("#from").val();
var last= $("#to").val();
console.log('fromWhere--'+initial);
console.log('to---'+last);
alert('Before Loop');
for (var i = initial; i <= last; i++) {
$('#rightMark_' + i ).val(rightMarkVal);
$('#wrongMark_' + i ).val(wrongMarkVal);
$('#selectData_' + i).prop('checked', 'checked');
}
$("#from").val('');
$("#to").val('');
}
</script>
The above JavaScript code working fine in first attempt means when I assign some value to initial and last variable then the loop iterates and works as expected and assign desired values to dynamically generated input fields, But now the problem is when I assign new value to initial and last variable then the loop not able to iterate any more.
And one more thing I want tell you all that all the dynamic IDs of input fields are generated correctly and I'm also getting the values which is going to be assigned to the input fields on second attempt and my HTML looks like following.
HTML
<div>
<div>
<ul>
<li>
<label>From</label>
<input name="" id="from" type="text" placeholder="from" value="" />
<label>To</label>
<input name="" id="to" type="text" placeholder="to" value="" />
<input name="rightMarkVal" id="rightMarkVal" type="text" placeholder="positive Value" value="" />
<input name="wrongMarkVal" id="wrongMarkVal" type="text" placeholder="Negative value" value="" />
<input type="button" class="btn btn-success" value="Assign Marks" onclick="callAssignMark()">
</li>
</ul>
</div>
<c:set var="counter" value="0" scope="page" />
<div>
<table>
<th>S.No</th>
<th>
<input type="checkbox" id="selectAllCheckBox">
</th>
<th>Right Marks</th>
<th>Wrong Marks</th>
<tbody>
<c:forEach var="list" items="${List}" varStatus="loop">
<tr>
<td>
<c:out value="${counter = counter+1 }" />
</td>
<td>
<form:checkbox path="qId" id="selectData_${counter}" value="${list.id}">
</form:checkbox>
</td>
<td>
<form:input path="rightMark" id="rightMark_${counter}" value="" />
</td>
<td>
<form:input path="wrongMark" id="wrongMark_${counter}" value="" />
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
I am unable to find out where is the problem so please help me.
Any help will be appreciated. Thanks

Related

Dynamically multiply 2 cells and display the result in a third cell using java script

I am pulling records from a db, displaying them in a table rows with form input fields. That means there will be multiple rows as seen in the sample html code below. I want to use javascript only. The idea is that when a user enters a quantity, it gets multiplied by the unit price and the result displayed in the sub total field. I am not JS developer, I searched and found the below code which is close to what I need. I will appreciate if someone can make some suggestions so as to get this code work.
<SCRIPT language="JavaScript">
<!--
function calculate() {
var Quantity = document.getElementsByName("Quantity").value;
var unitPrice = document.getElementsByName("unitPrice").value;
var total = 0;
for (var i = 0; i < Quantity.length; i++) {
total += parseInt(Quantity[i].value) * parseInt(unitPrice[i]);
}
document.getElementsByName("subtotal").value = total;
}
</SCRIPT>
<table>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2"/>
<input name="subtotal" size="2"/>
</td>
</tr>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2"/>
<input name="subtotal" size="2"/>
</td>
</tr>
</table>
A few things: a) document.getElementsByName("") returns a NodeList Collection of elements, so you cannot get the value of each input like that, you'll have to get them inside the for loop; b) then you also need to get the value of each unitPrice[i] inside the loop before parsing it and c) the total should be reset after each iteration, so can just have it inside the loop. See below:
function calculate() {
var Quantity = document.getElementsByName("Quantity");
var unitPrice = document.getElementsByName("unitPrice");
for (var i = 0; i < Quantity.length; i++) {
if (!Quantity[i].value) continue; // prevent NaN
let total = parseInt(Quantity[i].value) * parseInt(unitPrice[i].value);
document.getElementsByName("subtotal")[i].value = total;
}
}
<table>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2" />
<input name="subtotal" size="2" />
</td>
</tr>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2" />
<input name="subtotal" size="2" />
</td>
</tr>
</table>
In order to avoid getting NaN for the result which does not have any value, you can add if (!Quantity[i].value) continue; as the first line in the for loop, that should prevent it.

How to run jQuery function in input type text when input type text is in loop

#for (int i = 0; i < ViewBag.Count; i++) {
<tbody>
<tr>
<td> <input type="text" required readonly name="emp[#i].Total_Marks" value="#ViewBag.Total" class="form-control" id="tm" /></td>
<td> <input type="number" required name="emp[#i].Obtained_Marks" class="form-control" id="ob" /></td>
<td> <input type="number" required name="emp[#i].Percentage" class="form-control" id="percentage" onfocus="calcper()" /></td>
<td> <textarea cols="10" required rows="1" name="emp[#i].Remarks" class="form-control"></textarea></td>*
</tr>
</tbody>
}
function calculatePercentage() {
ab = $("#tm").val();
sb = $("#ob").val();
ntb = parseInt(sb) / parseInt(ab) * 100;
console.log(ntb);
document.getElementById("percentage").value = ntb;
}
I am new to mvc 5 and javascript/jQuery please help me how can I use this jQuery function in percentage in every input type which is created by loop but their id is same
As you said you need to call a function on your percentage textbox.
Let me tell you one thing assigning a same Id to a element is bad practice but you can have same name.
Recommend you to use common class attribute or common name attribute
<input type="text" name="percentage1" id="percentage1" class="percentage">
That you can consider as a empty class which will help you for your script operations
eg:
<html>
<head>
<script>
$('.percentage').keypress(function(){
alert('I called');
});
</script>
</head>
<BODY>
<input type="text" name="percentage1" id="percentage1" class="percentage" />
<input type="text" name="percentage2" id="percentage2" class="percentage"/>
<input type="text" name="percentage3" id="percentage3" class="percentage"/>
</BODY>
</HTML>
In the above code I have three textbox where it is pointed to same function which will show alert box.
In your case just apply the emp[#i] to the Id also and have a common class name or have a common name attribute which will help you.
Happy coding.

Script - Retrieve text input

I have several input in my html (this is one input for exemple) :
<TH>
<FORM>
<input name="designation" type="text" size="12" />
</FORM>
</TH>
So, I want retrieve the text input and show it. So I use this script :
$("#Compil").click(function() {
var n_input = document.getElementById("designation").value;
alert('Designation : ' + n_input); // -> n_input non defini (undefined)
});
But don't work. My alert don't display. Can you help me please?
PS : This a script in Javascript or jQuery please?
You are missing the id attribute on your input, simply change your html to include
<input id="designation" name="designation" type="text" size="12" />
1)in you script you getting the value by id designation but you didn't add id attribute like designation in your html input field .so only its throwing undefined error.
$("#Compil").click(function() {
var n_input = document.getElementById("designation").value;
alert('Designation : ' + n_input);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<TH>
<FORM>
<input name="designation" id="designation" type="text" size="12" />
<input type="submit" name="submit" id="Compil" value="submit" />
</FORM>
</TH>

Adding a item into a cart automatically using javascript

Hi i have a cart that i want to add a form automatically this code seems to kinda do the trick only the problem is i have to hit F5 for it to add the amount i am quite new to this and cant figure out where i have gone wrong.
<form method="post" action="level3.php" class="jcart" id="foo">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="ABC-8" />
<input type="hidden" name="my-item-name" value="Level 1" />
<input type="hidden" name="my-item-price" value="95.00" />
<input type="hidden" name="my-item-url" value="" />
<table>
<tr>
<td width="65%">
<strong>Level 1 all for £95</strong>
</td>
<td width="15%" align="right">
£95.00
</td>
<td>
<input type="text" hidden ="true" name="my-item-qty" value="1" size="3" hidden="true" />
</td>
<td width="20%" align="center">
<input type="submit" name="my-add-button" id="my-add-button" value="add" class="button" />
</td>
</tr>
</table>
<input type="hidden" name="visited" value="" />
</fieldset>
That is the form that submits the amount into the check out.
<script>
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1)
{
url = document.URL+"#";
location = "#";
} else {
location.reload(true);
document.getElementById("my-add-button").click();// Simulates button click this has to be in as it links to another piece of java that adds the item to the check out with out this it wont add the item
document.foo.submit(); // Submits the form without the button
}
});
</script>
document.getElementById("my-add-button").click();
The code above links to the code below that adds the items from to my knowledge
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
Thank you in advance for any help or suggestions
If i understand correctly, you increase some value of cart in PHP and than want to update quantity on page without refreshing page.
I made little JSFiddle: http://jsfiddle.net/7SbBA/
Basically use ajax:
$.ajax({
url: 'example.com',
data: /* pass product id here */
success: function(){
/* update quantity you want */
}
});
There is some html change too.
UPDATE
If you want updated total values on page load, just £<span class='amount'><?php echo $product['quantity'] * $product['price'] ?></span> and there is no need to use jquery/js for that. But if you still want dynamically update on window load, i updated my JSFiddle v.2

how to set form value with external select value

so i am using the play framework and I'm try to create multiple submit buttons that call the one form:
So what I have is a list of strings, and i would like to create two buttons that will go back to the server and complete an event, the first is send the second is cancel. What i would like to also do is set the source value equal to what is selected in the foo select object. How would I go about doing this? Do i need to create a javascript even that is fired from the form and then get the var inside that function and then fire off the submit? Im not 100% familiar with play framework and scala, so im not sure if i can get it somehow inside this code without using a new method.
#(myList: List[String], theForm: Form[Obj])
#import helper._
#main("myVar Controller") {
<select id="foo">
</select>
<table border="1">
<tr>
#for(myVar <- myList) {
<td>#myVar
#form(routes.Application.method()) {
<div id="hiddenForm" style="visibility:hidden">
<input type="text" name="commandID" id="commandID" value="10" /> //Send Code
<input type="text" name="source" id="source" value=**"Put selected value of foo here" />**
<input type="text" name="destination" id="destination" value="#myVar" />
</div>
<input type="submit" value="Send" />
}
#form(routes.Application.method()) {
<div id="hiddenForm" style="visibility:hidden">
<input type="text" name="commandID" id="commandID" value="18" /> //Undo code
<input type="text" name="source" id="source" value=**"Put selected value of foo here" />**
<input type="text" name="destination" id="destination" value="#myVar" />
</div>
<input type="submit" value="Undo" />
}
</td>
}
</tr>
</table>
}
First of all, the html isn't valid.
You should first make sure that there aren't elements that have the same id.
You have to use javascript to change a value in your form.
I'm not familiar with scalar or playframework, but if they allow you to use jQuery, I recommend the following solution.
$("#foo").bind("change", function(){$("#source").val($("#foo").val()));});​
example:
http://jsfiddle.net/RubenJonker/a8a8p/5
If they don't allow you to use jQuery, then you should put some javascript in the onchange event of the select.
<select onchange="document.getElementById('source').value = this.value">
</select>
example:
http://jsfiddle.net/RubenJonker/a8a8p/4
Incase anyone else has this problem I used the following to solve my problem: Thanks Ruup as your code was the reason why I solved the problem
html:
<select id="foo" >
<option></option>
<option value="test">test</option>
</select>
<input type="text" value="" name="field" id="field" />​
and javascript:
$(document).ready(function() {
obj = document.getElementById("foo");
obj.onchange = function()
{
var elements = document.getElementsByName('field');
for (i=0;i<elements.length;i++)
{
elements[i].value = $('#foo').val();
}
}; });

Categories