get 'for' value by javascript click - javascript

my problem is when I want get 'for' value by javascript, the javascript return only last value :/
the php
if($this->test % 2 != 0)
{
for ($z=$this->test+1;$z>=1;$z--) {
echo '<input type="submit" class="test" value="'.floor($z).'">';
}
the javascript:
$(".testi").click(function(){
var t = $(".testi").val();
alert(t);
});
why this javascript return only last value???

The JavaScript is returning only the last value because your HTML contains multiple fields with the same class name. So, you must use this in the jQuery code to get the current element that you clicked:
$(".testi").click(function(){
var t = $(this).val();
alert(t);
});

php is a string processing language, its main purpose is to output some sort of string, so the result is a set of strings.
js doesn't return anything, its just a programm which runs and reacts on some events, so there is no concatenation of strings or return values by default
Every time a click happens the function will execute, get the current value from .test1 and alert it.

Related

assign the value of `input ` to a variable but return blank in JS

I want to assign the value of input to a variable in Javascript, but I am not sure why the value of input is always blank.
Here is an example:
let input = document.getElementById('input').value
let val = 'not'
function check() {
//console.log(document.getElementById('input').value) will work
console.log(typeof input)
console.log(input)
}
<input id='input' type='text'>
<button onclick='check()'>Check</button>
The input value is blank (nothing), but the typeof input is string.
If I use document.getElementById('input').value, this will totally work which will display the value of input sucessfully.
Could anyone explain me a little bit why I assign it to a variable won't work?
Thanks for any responds!
Variable assignment val = 'not' takes place at the first time page load. When you need to assign dynamic value, like on a button click, you need an event handling mechanism (In your case, a click event). You are calling a function upon click, but not assigning any value to your variable there. Make assignment inside function like:
function check() {
val = document.getElementById('input').value
console.log(val)
}

Can't execute function in javascript

I've looked a lot in this website for an answer and honestly I've seen many close answers to my problem but still can't make it work.
I want to use a input textbox value and put it in javascript function then use javascript to calculate what I've given to the textbox for me and then put the answer to another paragraph in my html document (in this case I want to use kmh=ms*3.6 with return to do the calculation)
So this is my function code:
function msToKM() {document.getElementById('mstokm').innerHTML='<input type="text" name="mstokm" id="mstokmh" value="10"/>m/s<br><br><button type="button" class="buttons" onclick="convMSKM()" style="padding: 10px 10px;">Equals to!</button>';}
function convMSKM () {mstokm= document.getElementById('mstokmh'); mstokmA(mstokm);}
function mstokmA(ms) {return kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}
And I'm specificly having a problem with this part of the code:
function mstokmA(ms) {return kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}
because it's not executing the last part of it.
I can provide the html codes as well if needed.
How can I fix this?
Here's a demo how to do it
Well with onclick event i am selecting value of input field and than printing result in console. you can place it to any element you want instead of printing to console.
function handle(){
let val = document.getElementById('userIn').value;
console.log(3.6*val)
}
<input type='text' value='' id='userIn'/>
<button onclick='handle()'>calculate</button>
The return statement causes the function to stop executing, so what is happening is that you are returning value and it never gets to set that value inside the element. You can do something like this:
mstokmA(ms) {
document.getElementById('AmstokmA').innerHTML = ms*3.6;
}
OR more like you were trying to do:
mstokmA(ms) {
var kmh = ms*3.6; // set value inside variable
document.getElementById('AmstokmA').innerHTML = kmh; // append that value to the element
}
I prefer the first option.
I hope it helps ;).
Note: there is no need to return in this case.
Leave the return statement where it it, but replace "return" with "let".
Example:
function mstokmA(ms) {let kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}

JS Function calling displaying odd text & not working more than once

I have a problem, when I run my function "addMoney(amount)" (shown below) it works and shows the following: 100[object HTMLButtonElement]
My question is this, is there a way to get rid of the [object HTMLButtonElement] while keeping the number from moneyAmount when the function is called? And additionally, is there a way to call the function multiple times and add the money accordingly? As it only works the first time I call it, calling it more than once with the same or different amounts of moneyAmount displays no more or no less than what displays the first time.
My HTML:
<li class="item_shown" id="money">Shrill: <button class="moneyButton" id="moneyAmount">0</button></li>
Calling the function in HTML:
<a class="button" onclick="javascript:addMoney('100');">Add 100 Money</a>
My JS Function:
function addMoney(amount) {
document.getElementById('moneyAmount')
var newBalance = amount + moneyAmount;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
The text inside an element is considered to be a text node and since the button node has no other children, is the button node's first child. The text node's value (in this case "0") is the value of its nodeValue property. Assigning a new value to the nodeValue will change the text displayed. So in your case the following code should work:
function addMoney(amount) {
var node = document.getElementById('moneyAmount');
var textNode = node.childNodes[0];
var moneyAmount = parseInt(textNode.nodeValue, 10);
textNode.nodeValue = amount + moneyAmount;}
In your JavaScript, + moneyAmount; does not do anything. It returns what you see: [object HTMLButtonElement].
I think you want to add some numbers but it's not yet completely clear to me what you're trying to achieve. Could you elaborate?
Chris
EDIT:
Thank you for clarifying your question.
Try updating your function like this:
function addMoney(amount) {
var oldBalance = document.getElementById('moneyAmount').value;
var newBalance = amount + oldBalance;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
Try to find value by document.getElementById('moneyAmount').innerHTML and use some global variable say total_value to store retrieved value and then for each function call try to add the retrieved value to the previously stored value.

Trying to multiple two numbers entered in text fields and alert the answer using jquery

Very new to javascript and jquery. Attempting an exercise and came up with this code which I was hoping would take the two numbers a user enters into text fields and on clicking the multiply button, it would alert() the answer.
<body>
<script>
$(document).ready(function(){
var first = $('#first').value;
var second = $('#second').value;
$('#multiply').click(function(){
alert(first*second);
}); // end click
}); // end ready
</script>
First Number:
<input type="text" id="first"><br >
Second Number:
<input type="text" id="second"><br >
<input type="button" id="multiply" value="Multiply">
<input type="button" id="divide" value="Divide">
</body>
I'd suggest:
$(document).ready(function(){
$('#multiply').click(function(){
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
console.log(first*second);
}); // end click
}); // end ready
val() is used to get the value from a jQuery object (or the value of the first element of a jQuery collection),
parseFloat() is used to convert the <input/> elements' string into a number.
Incidentally, I'm using console.log(), instead of window.alert(), in order to be less frustrating the user. But, obviously, change that to your own taste (but logging to the console doesn't require a user-action to dismiss).
References:
JavaScript:
parseFloat().
jQuery:
val().
There is no value property in a jQuery object, use the val method to get the value from the inputs:
var first = $('#first').val();
var second = $('#second').val();
Right now you have the code for getting the values when the page loads, but you should get the values when the click happens:
$(document).ready(function(){
$('#multiply').click(function(){
var first = $('#first').val();
var second = $('#second').val();
alert(first * second);
}); // end click
}); // end ready
You are using implicit conversion from strings to numbers when you do the multiplication. You might want to explicitly parse the strings, it's good practice to make sure that the data is of the correct type rather than relying on implicit conversions. If you for example want to add numbers, the implicit conversion won't work there, as the + operator also is used to concatenate strings. Use the parseInt or parseFloat methods to parse strings into numbers. Example:
var first = parseInt($('#first').val(), 10);
var second = parseInt($('#second').val(), 10);
When you grab the value of a text field, the result is text. Not a number. You can parse the value into a number with the (globally available) parseFloat function (Or the parseInt function if there is no fractional value to the numbers).
var first = parseFloat($("#first").val());
var second = parseFloat($('#second').val());
$('#first') is a jQuery object, so you should use the .val() method. On the other hand, you are setting the variables when the DOM is ready, so it's not updating it when the user clicks.
$(document).ready(function () {
var first, second;
$('#multiply').click(function () {
first = $('#first').val();
second = $('#second').val();
alert(first * second);
});
});
In other things, your script tags should be at the end of the body. Script parsing is synchronous so the browser takes more time to get the DOM ready.
Have fun! :)

JavaScript populating and clearing <input> textbox

I got 6 "textboxex" and an Array with them.
<input id="slot0" type="text" /> id from 0 to 5, also Array named "slotarray". I want arrray and textboxes to be bound slotarray[0] with input id="slot0" etc.
First i needed function that will find first empty field in array (no matter if corresponding textbox is empty - but should) and put there string (short string - shortcode like "abc" or "sp1").
This function also need to populate bound textbox with long string.
If slotarray[2] == 'abc' then with the same number in ID (here be id="slot2") need to contain long string like "Abrasive Brilliant Conexant".
Here what i got
click to populate
and then function
function populate(shortstring,longstring) {
for (var i=0; i<6; i++) {
if (slotarray[i] == '') {
slotarray[i] = shortsrting;
slotid = 'slot' + i;
document.getElementById(slotid).value = longstring;
break;
}
}
}
With clearing at the moment of creating: ( Array('','','','','','') ), and textbox .value=''; its working as it should.
But then i figured out that i need function to clear textbox and bound array field. Not all but one specific for one clic. So instead of 6 functions i start to wrote
clear this field
for each of textbox, with different numbers and ids ofcourse, and clearing function:
function clear(arrayid, slotid) {
slotarray[arrayid] = '';
document.getElementById(slotid).value = '';
}
But this function do not clearing textbox neither array. I see that textbox has text, and i know that array isn't cleared because first function works finding first empty object...
What am i doing wrong here? its definition of "empty"/"cleared" filed/textbox? maybe i need to use more complex conditions? maybe it is something else.
Maybe i don't need array (i can manage to get rid of short-codes) and just make functions work only on textboxes?
Ok - i prepared jsfiddle demo with this, but even populating don't work..
http://jsfiddle.net/BYt49/11/
You can't use the keyword clear because refers to the (deprecated) function document.clear; so try to change the name of your "clear" function.
Ok, whatever you have written is fine. Just change to way you call your javascript.
Here is jsfiddle: http://jsfiddle.net/BYt49/20/

Categories

Resources