I would like to calculate the total price of the if check box is checked by using JavaScript
I'm not allow to separate the id to 2 section of by adding div
for example.
<form id="bookingForm">
<section id = "checkcost">
<h2>Total cost</h2>
Total <input type="text" name="total" value="$0.00" size="10" readonly />
</section>
</form>
First, i use this method get the id
var frm = document.getElementById('bookingForm')
i m trying to do by using the following code but this is not the correct method
frm.checkcost.total = calculate()
Since the input area to shows the total cost is inside the id="bookingForm", how should i display the total cost once the check box is checked??
ps: here is the link i had try but it didn't work, and now i'm trying other method
onclick in php echo with error invalid unexpected token
If there's only one field named total in the form, you don't need to worry about the section at all:
var frm = document.getElementById('bookingForm');
frm.total = calculate();
or
document.querySelector("#bookingForm [name=total]").value = calculate();
If you have multiple fields named total, then you just use the ID of the section:
document.querySelector("#checkcost [name=total]").value = calculate();
// ----------------------^
document.querySelector finds the first element that matches a given CSS selector. You can use the full power of CSS to find elements in the document. There's also document.querySelectorAll which finds a list of matching elements. Finally, individual elements also have both methods, which look only within those elements. So for instance, we could also do this:
var frm = document.getElementById('bookingForm');
frm.querySelector("#checkcost [name=total]").value = calculate();
(But that's just an example, not a suggestion; it's more round-about than necessary.)
Related
I have a PHP generated table that shows x number of rows based upon the number of product that is expected for that particular order. The idea is that a user can input an order number and the script will validate the input text against what is expected a return a Pass or Fail status.
This works for row 1, but after that it will not validate any of the other rows.
Reading about I am pretty sure it is due to duplicate id's, so i created a auto increment row field in the database to serve as the id. However it is beyond my skill to set the id as the row number and then validate against the order number.
Table Code:
if (sqlsrv_num_rows($getres) > 0) {
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
echo '<tr><th>Row</th><th>Works Order</th><th>Scan</th></tr>';
echo 'T-Clip Scan: <br/>';
echo '<br/>';
while ($add_info = sqlsrv_fetch_array($getres)){
$row = ($add_info['row']);
$worksorder = ($add_info['id']);
print ("<tr> <td/> $row <td/> $worksorder
<td/>
<input id= 'worksorder' value='' />
<p id='TR'></p>
<script>
document.getElementById('worksorder').onblur = function() {myFunction()};
function myFunction() {
var worksorder, test;
worksorder = document.getElementById('worksorder').value;
test = (worksorder == '".$_SESSION["worksorder"]."') ? 'PASS':'FAIL';
document.getElementById('TR').innerHTML = test;
}
</script>
</tr>");
}
Screenshot of issue
Any help it getting it to work for all rows is appreciated,
Thanks
The problem is likely because you're using creating <input id='worksorder'> and using document.getElementById('worksorder') to reference it within a loop.
HTML IDs are supposed to be unique on the page, so getElementById will only ever return a single element, that being the first element in the code that has the named ID.
If you want to do this in a loop, then you need to make sure that the ID for each element you generate is unique. Typically this would be done by adding the row ID to the generated HTML ID.
eg <input id= 'worksorder_{$add_info['id']}'> or similar, and then reference that in the JS code.
Alternatively, use an HTML class instead of an ID, since class names do not need to be unique, and then write your JS code to use document.querySelector() to query by classname instead of getElemenetById(). If you do it that way, then the JS code doesn't need to be in the loop, as it will be run once and apply to all the matching elements in one go.
You don't have to use a separate script for every row. You can create a single script to hande all the rows.
Firstly, provide ids to the <tr> tag and the <input> tag to receive the values and add an onblur listener. You can use the autoincrementing column value for the ids that you get from database.
e.g.
echo "<tr> <td/> $row<td/> $worksorder <td/>
<input id='".$id."' value='' /><p id='TR_'".$id."' onblur='myFunction(this)'></p>";
Also, add the onblur listener and pass the object to myFunction().
Then add a single myFunction() at the end.
<script>
function myFunction(param) {
var worksorder, test, id;
worksorder = param.value;
id = param.id;
console.log("order " +worksorder + ' '+id);
test = (worksorder == '".$_SESSION["worksorder"]."') ? 'PASS':'FAIL';
document.getElementById('TR_'+id).innerHTML = test;
};
</script>
This will handle all the rows for you. I hope it helps you.
Working JS fiddle
You are setting all the input fields with the same id. Html cannot handle same ids. You should either use incremental ids or use classes instead of ids, and adapt the JS function to use parameters, so not to have a JS function in every row. One function is enough and you can call it with the row number as parameter
HELP!!.... I can't dynamically access data entered by users into Input fields!
I'm a curriculum-designer trying to make a 'Matching'-activity (18-questions-with-18-scrambled-up-possible-answers), in which answer-choices get dynamically crossed out, 1 by 1, as they get 'used up' by the student, whenever (s)he types the letter of that choice (in this case "r") into the input-field. Here's the HTML for 1 of those 18 matches: (Hint: Pay attention to the "id"-attributes)
HTML
<input title="Question 18 - type 'R' into this input field"
class="questions" maxlength="1" id="18" onblur="My_Blur_Fx(this);">
</input>
<span class="r_as_selected, choices" id="r"> <!--I use the first class ('r_as_selected') in the J-Query example below, and the 2nd class ('choices') in the Javascript example below.-->
[Choice] R. (**All this span should soon be crossed-out.**)
</span>
I thought I could pull this off with a "change" event. However, neither my Javascript, nor my J-Query seems to be able to do it, because neither one can dynamically access the user's typed-in input (the very stuff that PHP would normally access via GET or POST).
J-Query
My J-Query-attempt to dynamically access this user-entered input...
$("input").change(function(){
$("input"[value="r"])
.add('.r_as_selected')
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'})
});
...failed because, although it could cross out the '#r' answer-choice, yet it would ALSO cross it out whenever they typed in ANYTHING....So the [value='r'] part of the code wasn't able to target JUST the field where someone had typed 'r'.
Javascript
My Javascript-attempt to dynamically access this user-entered input...
<script>
function My_Blur_Fx(x) {
var userInput = document.getElementById(x).value;
var userChoices = document.getElementsByClassName("choices").id;
var i;
for(i = 0; i < 18; i++)
{ if (userChoices[i].attributes[1].value == userInput) {
/*Note: "attributes[1] is my way of accessing the 2nd attribute in the HTML span above, which is 'id="r"'*/
userChoices[i].style.textDecoration = "line-through";};
};
}
</script>
...failed too because an 'Input' is an "Element" whose "Value," is defined by the DOM to be "NULL,"...so line 3 above gives an error. Neither could any of the other potentially-relevant DOM-modifiers, instead of .value (i.e. .innerHTML / .nodeValue / .attributes) access that user-entered value. So it seems that 'Input' elements just can't be accessed dynamically. . . . ( Any suggestions...J-Query, Javascript, or other? )
You can't use an attribute selector to match user input, it only matches the static attributes, not the dynamic values. You can use .filter() to search for an element that matches a selector and has a specific value.
$("input").change(function() {
$("input").filter(function() {
return this.value == 'r';
}).add(".r_as_selected")
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'});
});
You have several problems in MyBlurFx().
document.getElementById(x).value won't work beceause x is the element, not its ID. You should just use x.value.
document.getElementsByClassName("choices").id won't work because getElementsByClassName() returns a NodeList, not a single element, so it doesn't have an id property. But you don't need the ID, just use document.getElementsByClassName("choices"), since the for loop operates on the elements, not IDs.
Maybe there is more than one mistake, but I see that your code $("input"[value="r"]) is same as $(undefined). You must use $('input[value=\'r\']') instead.
I can not access this data within the div with javascript.
<div class="questions-text-alignment whiteTextWithShadow question-size-v4">
DATA HERE
</div>
Any suggestions?
Way 1
You can access the data using jQuery in the following way:
<script>
$(document).ready(function(){
var data = $(".questions-text-alignment").html();
alert(data);
})
</script>
Way 2
Without jQuery:
<script>
var data = document.getElementsByClassName("questions-text-alignment");
alert(data[0].innerHTML);
</script>
You can access using document.getElementsByClassName(), But the thing is you will get an array object. Using the array you have to find out yours. In the below sample I have assumed only one class available.
var arr = document.getElementsByClassName("question-size-v4");
alert(arr[0].innerHTML);
DEMO
You can try like this
<script>
function getHtml() {
var html = document.getElementsByClassName("questions-text-alignment")[0];
alert(html.innerHTML);
}
</script>
<div class="questions-text-alignment whiteTextWithShadow question-size-v4">
DATA HERE
</div>
<input type="button" name="click" value="click" onclick="getHtml()" />
You should Use Id to select element in this scenario -
DEMO
<script>
function changeData() {
document.getElementById('contentDiv').innerHTML= "Updated Content";
}
</script>
<body>
<div id="contentDiv">
Content Of My Div
</div> </br>
<input type = "button" onClick = "changeData()"
value = "change div text" />
</body>
#StevenTang I exactly got stuck on the same problem and here is my solution.
document.getElementsByClassName("question-size-4")
works fine on full HTML document load and only if you have a single DIV object identified by this class name.
Otherwise you get HTMLCollection object for preview via ChromeTools to be opened in your web browser.
To identify individual DIV object, including your Class name and Data Here use Firebug and select your Data and open in Firebug with right mouse click (submenu select).
Once your DIV object selected and identified to include your class name and your Data Here is opened in console.log (Chrome tools), clicking on HTMLCollection you get every DIV object identified by index (natural number) as in array.
Selecting the correct index (natural number), you can access your Data Here via
elements = document.getElementsByClassName("question-size-4");
DataHere = elements[correct DIV index].innerHTML or .innerText
You need to manipulate
x = elements.length;
first to know if any such DIV object identified by your class name really exists and has been downloaded.
If x = 0 it means HTMLCollection is empty and elements.innerHTML generates undefined string
If x = 1 there is exactly a single DIV identified by your class name, so
elements.innerHTML should work fine
If x > 1; you have got more DIV objects identified by your class name, so you needd to select the correct one from array data stracture, entering correct index, as above.
It took me months to study the problem and to find the correct answer.
thank you
I have multiple forms in a single page.
Every form is is in different <div>, I want to insert some values in html inputs, present in a specific <div>, Please tell what I am doing wrong?
function onLoadPopulateInputs(){
var digits = getDateTimeOnLoad();
console.log("DT "+digits)
$('.input').value = digits #I think here is someting wrong!!!
}
google.setOnLoadCallback(onLoadPopulateInputs);
My Input looks like this:
<input size="16" type="text" readonly>
$('#yourDiv > input').val(digits)
your selector is borked
function onLoadPopulateInputs(){
var digits = getDateTimeOnLoad();
console.log("DT "+digits);
var $yourDiv = $('#yourDiv');
$yourDiv.find('input').val(digits);
}
google.setOnLoadCallback(onLoadPopulateInputs);
I would add a class for div containing 'forms' :
<div class="formDiv">
<input />
....
</div>
<div class="formDiv">
<input />
....
</div>
JS
$('.formDiv').each(function(){
var $form = $(this);
$form.find('input').each(function(){
$(this).val(someValue);
});
});
Usage exemple http://jsfiddle.net/techunter/EzWpu/
Why this instead of just $('input') or $('#myDiv input') like proposed by other?
Well because here you can manage context and control everything. also you said you have multiple forms inside multiple div : "multiple" == make it generic and use class not id. If you need to edit a specific value maybe consider faster selection using ID or $('#myDiv input[name="myInputName"]) or equivalent
You need to use .val
$('.input').val(digits);
give your specific div an id and call an id selector..
function onLoadPopulateInputs(){
var digits = getDateTimeOnLoad();
console.log("DT "+digits)
$('#divID input').val(digits);
}
jquery method of setting a value of input is .val() and not .value
I have this code in jquery :
$("#order_btn").click(function(){
var totalprice = $(".price_amount").text();
$("#totalprice").val(totalprice);
});
When I submit this form with a hidden value i will get the totalprice value two times, if its 200000 i will get 200000200000. why ?
<input type="hidden" value="" name="totalprice" id="totalprice">
<input id="order_btn" type="submit" class="submit" name="submit" value="submit">
the price amout will defined here :
<span class="price_amount">75000</span>
I have this span tag two times, but I need both of them, is there a way to get one value only ?
you most probably have more than one span tag with class "price_amount"
try using
var totalprice = $(".price_amount:first").text();
or
var totalprice = $(".price_amount:eq(0)").text();
// therefore you can access the second span tag like this
var totalprice = $(".price_amount:eq(1)").text();
// and so on...
if this makes it work, check your code for a superfluous span tag
EDIT:
should be right now
EDIT 2:
if your totalprice variable should be the sum of all you "price_amount" spans, consider following:
var totalprice = 0;
$.each($('.price_amount'),
function()
{
totalprice += parseInt($(this).text());
});
Are you sure there's only one element on your page with the price_amount class? If you put a breakpoint (or an alert) on the value of totalprice after it's been assigned what do you get?
One other thing - and I'm not sure if this matters or not, but I would put this code in a handler for your form submit instead of click.
Because you have two <span> elements with the class "price_amount".
It's this line in particular
var totalprice = $(".price_amount").text();
When you call .text() from a jQuery set, it will aggregate that value for all selected nodes and return it.
So, either make sure you have only one span w/that classname, or make your selector more specific/granular so that you only retrieve the desired node.