Javascript innerHTML change not working - javascript

I hate to come here with what is seemingly a simple issue to solve but I'm stumped, and have tried multiple solutions.
I have a checkboxes, so that when clicked they will run a function that will change the total price of the cart however I can't even get a simple innerHTML change on the textbox that will display the total price with the onclick event.
HTML/php:
<?php
....
....
echo "<span class='chosen'><input type='checkbox' name='event[]'
value='{$event['eventID']}' title='{$event['eventPrice']}'
onclick='price_calc(this.title, this)'/></span>"
?>
<div id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</div>
....
....
<script src="bookingJS.js"></script>
</body>
As you can see the elements are all loaded into the DOM before the javascript runs.
JS:
function price_calc(price, chkbx) {
document.getElementById('total').innerHTML = 'Hello';
alert(document.getElementById('total').innerHTML);
}
Thank you for any tips in advance.

"total" is a field.So, try document.getElementById('total').value
innerHTML is for non field elements like span,div etc..

To set a input[type=text] value, you use .value not innerHTML:
function price_calc(price, chkbx) {
document.getElementById('total').value = 'Hello';
alert(document.getElementById('total').value);
}

try this:
document.getElementById('total').value="Hello";
alert(document.getElementById('total').value);

Related

Javascript concat clearing input fields

function js() {
document.getElementById("example").innerHTML = document.getElementById("example").innerHTML+"<input type=\"text\" name=\"name\" />";
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
I have a form, which need variable number of input types.
<form action="" method="">
[...]
<div id="mezok">
<div id="input_id">
<input type="text" name="name" />
</div>
</div>
[...]
</form>
I add and remove further inputs (along with their divs!) via an ajax call. Javascript calls a php which generates a new input_id div, and then concatenates to the rest of the div id="mezok". Adding and removing inputs are fine as long as everything is empty. However, when I add a new div when there is something in the input, it clears the rest of the inputs.
document.getElementById("mezok").innerHTML = document.getElementById("mezok").innerHTML+http.responseText;
document.getElementById("mezok").innerHTML += http.responseText;
document.getElementById("mezok").innerHTML.concat(http.responseText);
(The last one is not working at all...)
TL;DR: concat input to input, values of inputs disappear. :'(
Don't use innerHTML. What you are doing is redrawing the entire container contents, deleting existent inputs and creating new inputs each time. My experience says that when you are accessing innerHTML, recheck your code as you are probably doing something weird.
What you have to do is to create inputs individually and append them to the container, without touching the rest of the inputs. Is like appending elements to an array.
This way the code is more self-explanatory, and better, is way more performant:
function js() {
var input = document.createElement("input"); // Create a new input element. Is like "<input>".
input.setAttribute("type", "text"); // Set the 'type' attribute to 'text'. Is like having '<input type="text">'
input.setAttribute("name", "name[]"); // Set the 'name' attribute to 'name[]'. Is like having '<input name="name[]">' but because you already have set the type, now is like having '<input type="text" name="name[]">'
document.getElementById("example").appendChild(input); // Push it to the container
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
The code below could be a solution for you. In this way you're not going to overwrite the existing inputs with the associated values while you're adding new inputs.
function js() {
var inputElementToAppend = document.createElement('input');
inputElementToAppend.innerHTML = "<input type=\"text\" name=\"name\" />";
document.getElementById("example").appendChild(inputElementToAppend.firstChild);
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
Let me know if this worked for you.
Following working fine for me.
<button onclick="myFunction()">Try it</button>
<p id="demo">ABC</p>
<script>
function myFunction() {
var x = document.getElementById("myP").innerHTML;
document.getElementById("demo").innerHTML += `<input type=\"text\" name=\"name\" />`;
}
<script>
I would recommend to use appendChild and removeChild instead of innerHTML

Input Text Box Returns Undefined in Javascript

Here is my HTML:
<form name='cred' class="panel-body2">
<div class="form-group">
<label for='addjidlbl'> Username (JID):</label>
<input type='text' id='addjid' />
</div>
<input type='button' id='add' value='add' />
</form>
Here is the JavaScript:
$('#add').bind('click', function() {
var jid = $('#addjid').value;
alert(jid);
//var jid=document.getElementById('addjid').value;
var jid2 =$('#addjid').get(0).value;
alert(jid2);
// //$('#addjid').get(0).value;
log('jid=>'+jid);
var data = document.getElementById("addjid").value; //$(".panel.panel-default2#addjid").value;
alert(data);
alert("type=>"+ typeof(jid));
addRoster(jid);
});
function addRoster(jid) {
log('addRoster=>' + jid);
}
What I get are two message boxes with "undefined" and third with "type=>undefined". Why can't I get the input text of the addjid text box?
If I change var jid = $('#addjid').get(0).value;, jid is just blank even when the textbox has value. Why?
Change .value to .val() like
$('#addjid').value
should be
$('#addjid').val()
Here you have it working using .val()
add some text to the text box and
click on the add button and the alert will popup
$('#add').on('click', function() {
alert($('#addjid').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='cred' class="panel-body2">
<div class="form-group">
<label for='addjidlbl'> Username (JID):</label>
<input type='text' id='addjid' />
</div>
<input type='button' id='add' value='add' />
</form>
If I understand correctly, you want:
$('#addjid').val()
Since you are using id's to get the value you will only have one element with the given id. When you do .get(0) or any index you are typically trying to get the value out of a given array of values. For Ex
<li>first</li> //0
<li>second</li> //1
Here in a structure like this you will do something like
$("li").get(0)
It will give you the first item with in li.
and to get the value you will need to use .val()
So you can use
$('#addjid').val()
Hope this helps you.
Happy Learning :)

show and hide div after submiting an action when checkbox is check and uncheck

I am trying to show or hide div after submitting an action. so let say I have textarea and I put "example" there then checked the checkbox. after submitting, the "receipt.php" page must display "example" , and if I unchecked the checkbox and submit, the receipt.php page must hide the "example". I tried searching similar to my problem but I really don't have idea how to solve it. I have this code so far but i dont have any codes in "receipt.php" since I really don't have idea. pls help me
<form method ="POST" action ="receipt.php">
<textarea name ="comment"></textarea><br>
<input type="checkbox" id="checkbox" value ="1" >Show this comment in receipt<br>
<input type ="submit" value ="Print">
</form>
You don't need the server response to recognize if the checkbox was checked unless you have some validation on server side. If using JQuery, you can do this:
$('#checkbox').change(function(){
$('#your_div').toggle();
});
If you want to rely on what your server says you need to return something to your ajax call.
for example {response: true/false}
In Html:-
<form method ="POST" action ="receipt.php">
<textarea name ="comment"></textarea><br>
<input type="checkbox" name="reciept-chk" id="checkbox" value = "1" >Show this comment in receipt<br>
<input type ="submit" value ="Print">
</form>
In receipt.php:
<?php
..//recept.php
if(isset($_POST['reciept-chk'])){
// Write Code example here
}
?>
If you want to validate it client side before posting your value in receipt.php then
you can simply validate by piece of jquery.
$(document).ready(function(){
$('#checkbox').change(function(){
if ($('#checkbox').is(':checked')) {
$("#exampleDiv").show();
} else {
$("#exampleDiv").hide();
}
});
});
Please avoide toggle() as it deprecated in 1.8
Here is the code you'll need in your unique PHP file :
<form method="POST">
<textarea name="comment">
<?php (isset($_POST['checkbox1']) && $_POST['checkbox1'] == '1') ? echo "Example"; : echo ""; ?>
</textarea>
<br>
<label for="checkbox1">Show this comment in receipt</label>
<input type="checkbox" id="checkbox1" name="checkbox1" value="1" />
<br>
<input type="submit" value="Print" />
</form>
Replace what you want in place of "Example".
If you are using javascript only, you might try something like this:
<script>
function show(){
if(form.toggledisplay.checked == false){
document.getElementById('example').style.display = "none";
}
else{
document.getElementById('div').style.display = "block";
}
}
</script>
<form method = "POST" action="receipt.php" onsubmit="show()">
<textarea name = "comment"></textarea><br>
<input type="checkbox" name="toggledisplay" id="checkbox" value = "1" >Show this comment in receipt<br>
<input type = "submit" value = "Print">
</form>
<div id="example" style="display:none;">This is the div you want to show</div>
If you are populating the contents of the div from the receipt.php file, you could make a post request to it, when the onsubmit() function is fired and fill the contents of the div like:
document.getElementById('div').innerHTML = "Result from the get/post request"
Hope this points you in the right direction.

jquery multiply 2 textboxs then show the solution

I have this code that is not working. I am trying to multiply 2 textboxs and show the solution, but it doesn't show anything when I click. The code I have so far is this... what can be wrong with the code below?
<script type="text/javascript">
$('#AddProduct').click(function() {
var totalPrice = $('#debt').val() * $('#income').val();
$('#solution').val() = totalPrice;
});
</script>
<form name="form" method="post" action="">
<table>
<tr>
<td><input type="text" name="income" id="income" /></td>
<td><input type="text" name="debt" id="debt" /></td>
<td><input type="text" id="solution" name="solution" /> </td>
</tr>
</table>
</form>
Your jQuery needs to be:
$('#AddProduct').click(function() {
var totalPrice = parseInt($('#debt').val()) * parseInt($('#income').val()); // you can't multiply strings
$('#solution').val(totalPrice); // This is how you use .val() to set the value.
});
This is the way that you'd set the value of the solution textbox:
$('#solution').val(totalPrice);
Also, do you actually have an element with an id of 'AddProduct' on your page?
var totalPrice = $('#debt').val() * $('#income').val();
$('#solution').val(totalPrice);
Demo
After, you add jquery to your page as below
<script src="http://code.jquery.com/jquery-latest.js"></script>
you can do the following:
$('#AddProduct').click(function() {
var totalPrice = parseInt($('#debt').val(),10) * parseInt($('#income').val(),10);
$('#solution').val(totalPrice);
});
You have to tell it you want the value of the input you are targeting.
And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.
Providing 10 assumes you are wanting a base 10 number.

How to get value of a select option that was written on the fly with innerHTML = "<option>";

I have writen options to a <select> using something like
Id.innerHTML = "<option value='foo'>Foo</option>";
But on submission i get no value from the option? How can i correct this?
with forms, if you show/hide dynamic fields, alot of times, you have to have hidden values to store the values in and then have your PHP (or whatever) look for the hidden field value, instead of the dynamic HTML value. It's a pain
Thanks Roy i have thought about what you said and came up with the following:
function insert(){
document.getElementById('text').value = document.getElementById('select').value;
}
function insertHTML(){
document.getElementById('div').innerHTML = "<select id='select' onload=\"insert()\" onclick=\"insert()\"><option value='1'> 1 </option><option value='2'> 2 </option></select>";
}
<form method='post' action='http://localhost/test.php'>
<input type='button' value='insert' onclick="insertHTML(); insert();" >
<div id='div' ></div>
<input type='hidden' id='text' name='text'>
<input type='submit' value='go'>
</form>
Get input name instead of the name of the select.

Categories

Resources