I've the follow code for get the value fot two input and send it to a Ajax file for proccess it. It doesn't work and I put an alert for see what's wrong and the alert return me [object HTMLInputElement].
<tr>
<td>Introduzca licencia: </td>
<td><input type="text" id="lic" name="lic" value=""/></td>
</tr>
<tr>
<td>Introduzca apellidos: </td>
<td><input type="text" id="ape" name="ape" value=""/></td>
</tr>
<script type="text/javascript">
var lic=document.getElementById("lic").value;
var ape=document.getElementById("ape").value;
</script>
<tr>
<td><input type="button" value="Buscar" onclick="load(lic, ape);"/></td>
</tr>
If I try that it return the value of the input
<script type="text/javascript">
function prueba(){
var lic=document.getElementById("lic").value;
var ape=document.getElementById("ape").value;
alert("La licencia es: "+lic+" y los apellidos son: "+ape);
}
</script>
<tr>
<td><input type="button" value="Buscar" onclick="prueba();"/></td>
I don't know why the first code doesn't work if I'm making the variables of the same way.
In the onclick handler (load(lic, ape);) for <input type'='button'> in the first code block, neither the load function nor the two arguments (lic and ape) are defined.
Change it to:
onclick="load();"
and make your script file as:
function load(){
var lic = document.getElementById("lic").value,
ape = document.getElementById("ape").value;
alert("lic is " + lic); // test
alert("ape is " + ape); // test
}
DEMO
P.S. You are missing <table> tags. And document.getElementById will always return a DOM object.
Related
I have a hard JS/jQuery riddle ! Hard because I couldn't find it on Google nor here, neither now, nor months ago when I was looking for it previously.
A large framework is using checkboxes in a table:
<table class="ListTable">
<tr>
<td><input name="blnChecked[70_20]" type="checkbox" value="1" id="some_unusable_gobbledy_gook" /></td>
<td></td>...
</tr>
<tr>
<td><input name="blnChecked[71_20]" type="checkbox" value="1" id="some_more_unusable_gobbledy_gook" /></td>
<td></td>...
</tr>
<tr>
<td><input name="blnChecked[70_25]" type="checkbox" value="1" id="some_further_unusable_gobbledy_gook" /></td>
<td></td>...
</tr>
</table>
I now need to collect all checkbox name references into an array: 70_20, 71_20 and 70_25 in the above example. Then join them up, and submit them as a URL parameter to a different page (although this joining is not essential to my question).
Question: Using JS/jQuery on the same page, how do I get these references from the name strings in these (checked) checkboxes in an array ?
I prefer not to use regexes (a bit messy, or 'overkill' for such a seeming trivial matter imho), although such a solution is not off my table.
(If someone asks why the table is structured as such: This is not my doing. But I can see that when such a form, in which this table is submitted to a PHP page, the PHP stores all such checkboxes into a single array, which is very nice, and I wanted to achieve a similar effect with JS/jQuery.)
A way to create on client side the array is based on using:
.map()
string .replace()
$('#btn').on('click', function(e) {
var retVal = $('table.ListTable :checkbox[name^="blnChecked["]:checked').map(function(idx, ele) {
//
// if the name value has always the same format...
//
return ele.name.replace('blnChecked[', '').replace(']', '');
//
// or....
//
// return ele.name.split('[').pop().replace(']', '');
// return ele.name.substr(11, 5);
//return ele.name.replace(/blnChecked\[(.*?)\]/g, '$1')
}).get();
var param = $.param({'param': retVal.join(',')});
console.log('Array: ' + retVal);
console.log('URL param: ' + param);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="ListTable">
<tr>
<td><input name="blnChecked[7125_2355]" type="checkbox" value="1" id="some_unusable_gobbledy_gook" /></td>
<td></td>
</tr>
<tr>
<td><input name="blnChecked[71_20]" type="checkbox" value="1" id="some_more_unusable_gobbledy_gook" /></td>
<td></td>
</tr>
<tr>
<td><input name="blnChecked[70_25]" type="checkbox" value="1" id="some_further_unusable_gobbledy_gook" /></td>
<td></td>
</tr>
</table>
<button type="button" id="btn">Click Me</button>
This function isn't working. Can anyone please help? When I press the validate button, nothing happens.
<script>
function validate()
{
int user = document.getElementById("uname");
if(user=="rohit")
document.getElementById("btnsubmit").value = "Sucess";
else
document.getElementById("btnsubmit").value = "Fail";
}
</script>
<body>
<div>
<table id="tbl-aut">
<tr>
<td colspan="2"><h2>Enter Login Details</h2></td>
</tr>
<tr>
<td >Username<span style="color:red">*</span></td>
<td><input type="text" ></td>
</tr>
<tr><td colspan="2" align="center"><input id="btnsubmit" type="button" value="Validate" onclick="validate()"><td></tr>
</table>
</div>
</body>
Nothing is happening because you have a few problems:
First, you have a syntax error. int is not a valid keyword in JavaScript. In JavaScript, data types are implicitly determined. You cannot explicitly specify a type (and there is no integer type in JavaScript anyway).
Next, you are attempting to check an object (the text field) against the value stored in the object. You need to access the value property of the text field to get the data entered into it.
Also, you are attempting to get an object with an id of uname, but you didn't set up that id in the text field at all.
Lastly, and this is more of a best-practice thing. Always wrap the true/false branches of your if statements with curly braces {}. Although it is syntactically OK to omit them when there is only one statement in the branch, this is a well-know bug magnet.
<script>
function validate() {
var user = document.getElementById("uname");
if(user.value =="rohit"){
document.getElementById("btnsubmit").value = "Sucess";
} else {
document.getElementById("btnsubmit").value = "Fail";
}
}
</script>
<body>
<div>
<table id="tbl-aut">
<tr>
<td colspan="2"><h2>Enter Login Details</h2></td>
</tr>
<tr>
<td >Username<span style="color:red">*</span></td>
<td><input id="uname" type="text" ></td>
</tr>
<tr><td colspan="2" align="center"><input id="btnsubmit" type="button" value="Validate" onclick="validate()"><td></tr>
</table>
</div>
</body>
I have some issues with calculating some stuff with JS and getting the right values out of the input fields (number). When I use this code it doesn't show anything. So what is wrong with my JS? Do I need to include a jQuery file?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td><input type="number" name="TotalProductionTime" placeholder=""> hours</td>
</tr>
<tr>
<td>Breaks</td>
<td><input type="number" name="Breaks" placeholder=""> minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td><input type="number" name="Malfunctions" placeholder=""> minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td><p id="test"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" name="Calculate" value="calculate">
<script>
function Calculate()
{
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
</script>
</body>
</html>
You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle
You you are trying to get elements by their ID, but you don't give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.
function Calculate() {
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td>
<input type="number" id="TotalProductionTime" placeholder="">hours</td>
</tr>
<tr>
<td>Breaks</td>
<td>
<input type="number" id="Breaks" placeholder="">minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td>
<input type="number" id="Malfunctions" placeholder="">minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td>
<p id="test"></p>
</td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
</form>
Every id must be converted to integer. Example
var Malfunctions = parseInt(document.getElementById("Malfunctions").value);
then your ready to go
With HTMLInputElement you can use property .valueAsNumber which returns a numeric property if possible:
const str = document.querySelector("input").value;
const num = document.querySelector("input").valueAsNumber;
console.log(typeof str, str, str + 2);
console.log(typeof num, num, num + 2);
<input type="number" value="40" disabled />
You've got two problems here. One obvious is that you try to get a reference to the form inputs by id, but didn't give them any (you gave them a name). To fix, either change the name attribute to an id, or use the form-specific way to reference them, e.g.:
var TotalProductionTime = document.forms.frm1.TotalProductionTime
Second problem is more vicious and has to do with the scope of execution of what you put in onclick attributes. You see, your button is named "Calculate" just like your function, and in the context of the onclick attribute, its parent form is used to resolve identifiers before the global scope. So instead of calling the function named Calculate, you're trying to call the button itself. Fix that by giving them different names, referencing window.Calculate explicitly, or much better, define your event handler in JavaScript instead of using the HTML attribute:
document.forms.frm1.Calculate.onclick=Calculate
I am new to this forum and I want to be able to get a value from my html inputs into javascript. Right now i have this code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PWS</title>
</head>
<body bgcolor="#009933" text="#FFFFFF">
<H1 align="center">PWS Julia en Sophie</H1>
<hr>
<br>
<strong>DOUCHE</strong>
<table>
<tr>
<td>Temperatuur</td>
<td><input type="text" name="dtemp" onClick="calculateTotal()" /></td>
</tr>
<tr>
<td>Tijd</td>
<td><input type="text" name="dtijd" onClick="calculateTotal()" /></td>
</tr>
<tr>
<td>Hoe vaak per week</td>
<td><input type="text" name="dfreq" onClick="calculateTotal()" /></td>
</tr>
</table>
<br>
<strong>BAD</strong>
<table>
<tr>
<td>Temperatuur</td>
<td><input type="text" name="btemp" onClick="calculateTotal()" /></td>
</tr>
</tr>
<tr>
<td>Hoe vaak per week</td>
<td><input type="text" name="bfreq" onClick="calculateTotal()" /></td>
</tr>
</table>
<script type="text/javascript">
var dTemp = document.getElementsByName("dtemp").value;
document.write(dTemp);
</script>
obviously, its not working. Because the dTemp value stays undefined.
Can anyone help me, thanks in advance,
Bob
document.getElementsByName returns an array, so you have to reference the position of the element:
var dTemp = document.getElementsByName("dtemp")[0].value;
I would also recommend giving ID's to your inputs, since it seems that each name is unique in your case, that way you could use document.getElementById
document.getElementsByName("dtemp") will give you array of elements, traverse through one by one and get the value from it.
var elements = document.getElementsByName("dtemp");
var firstValue = elements[0].value;
1) You need to index the result of getElementsByName, as described in other answers; append [0] to document.getElementsByName("dtemp").
2) You can’t use document.write in code that is executed after the page has loaded. It would replace the current document by the written content. Write to an element instead.
3) You have not defined the function calculateTotal at all. Wrap your JavaScript code in a function, e.g.
<div id=result></div>
<script>
function calculateTotal() {
var dTemp = document.getElementsByName("dtemp")[0].value;
document.getElementById('result').innerHTML = dTemp; }
</script>
4) You have a long way to go, since now your code makes no attempt at calculating anything, you should hardly use onclick on an input element to start the calculation (rather, onchange on it, or onclick on a separate button element). You should read a good JavaScript primer, really.
I really don't understand why this is being so hard for me to get working:
http://jsfiddle.net/jp2code/qCExy/
It will eventually be going into an ASP.NET control, so I believe I need to pass Javascript the <textarea> control's ID.
It doesn't work.
So, in the jsFiddle, I tried using standard controls for First and Last names, but they don't work either.
EDIT:
I've been playing around with the jsFiddle, and it appears that my jsOnFocus is never called (alert never fires). However, I was able to run down a little script from someone else that makes the multiline textbox clear and reset - I just can't seem to find a way to call this from a javascript function:
function jsOnFocus(obj) {
alert("Inside the jsOnFocus.");
if (obj.Value==obj.defaultValue)
obj.Value="";
}
function jsOnBlur(obj) {
if (obj.Value==="")
obj.Value=obj.defaultValue;
}
Here is the HTML.
<table>
<tr><td>Message:</td><td> </td></tr>
<tr>
<td> </td>
<td>
<textarea name="txtMsg" rows="6" cols="30"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>
</td>
</tr>
<tr>
<td>Test1:</td>
<td><input type="text" name="txtTest1"
onfocus="jsOnFocus(txtTest1)"
onblur="jsOnBlur(txtTest1)" value="Test1" /></td>
</tr>
<tr>
<td>Test2:</td>
<td><input type="text" name="txtTest2"
onfocus="if(this.value=='Test2'){this.value=''};" value="Test2" /></td>
</tr>
<tr>
<td>Test3:</td>
<td><input type="text" name="txtTest3"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value==='')this.value=this.defaultValue;" value="Test3" /></td>
</tr>
</table>
"Message" works, but I'd like to get the code to running in a javascript that I can place in my "js" file and use on other objects.
"Test1" is an attempt to call the javascript, but it does not work.
"Test2" works, but it does not use the technique in "Message".
"Test3" works, and it does use the technique in "Message".
Does anyone see how to make this code work in the javascript instead of inline html?
jsFiddle Link: http://jsfiddle.net/jp2code/qCExy/10/
I played around a bit with your fiddle. I'm a newb when it comes to jsfiddle though so I did not dare to try to save my changes.
Anyway, there are a few things that keep the Test1 box from working. First of all, the script in the "JavaScript" block in the fiddle is added to the page like this (check by viewing source in the Result section):
<script type='text/javascript'>//<![CDATA[
window.addEvent('load', function() {
function jsOnFocus(obj) {
alert("Inside the jsOnFocus.");
if (obj.Value==obj.defaultValue)
obj.Value="";
}
function jsOnBlur(obj) {
if (obj.Value==="")
obj.Value=obj.defaultValue;
}
});//]]>
</script>
So your functions are not in a scope (for lack of a more precise term) where you can call them like you tried to do.
To fix this I added the script directly in the Html section inside as <script> block.
There was also a small issue with the javascript code itself. The value property is called value, not Value.
Also, I changed the onfocus and onblur attributes on the input to pass this to the functions. You can of course change it to pass an id if you want and then look up the control using the id. In that case make sure that the control has an id specified.
Anyway, here is the resulting code from the Html section of the fiddle:
<script type="text/jscript">
function jsOnFocus(obj) {
if (obj.value==obj.defaultValue)
obj.value="";
}
function jsOnBlur(obj) {
if (obj.value==="")
obj.value=obj.defaultValue;
}
</script>
<table>
<tr><td>Message:</td><td> </td></tr>
<tr>
<td> </td>
<td>
<textarea name="txtMsg" rows="6" cols="30" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>
</td>
</tr>
<tr>
<td>Test1:</td>
<td><input type="text" name="txtTest1" onfocus="jsOnFocus(this)" onblur="jsOnBlur(this)" value="Test1" /></td>
</tr>
<tr>
<td>Test2:</td>
<td><input type="text" name="txtTest2" onfocus="if(this.value=='Test2'){this.value=''};" value="Test2" /></td>
</tr>
<tr>
<td>Test3:</td>
<td><input type="text" name="txtTest3" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value==='')this.value=this.defaultValue;" value="Test3" /></td>
</tr>
</table>
Code Behind:
string strUserName = "User Name";
string strPassword = "Password";
txtUserName.Text = strUserName;
txtPassword.Text = strPassword;
txtPassword.Attributes.Add("onblur", "PasswordBlur(this, '" + strPassword + "');");
txtUserName.Attributes.Add("onblur", "UserNameBlur(this, '" + strUserName + "');");
txtUserName.Attributes.Add("onfocus", "UserNameFocus(this, '" + strUserName + "');");
txtPassword.Attributes.Add("onfocus", "PasswordFocus(this, '" + strPassword + "');");
Java Script:
function UserNameBlur(txtElem, strUserName) {
if (txtElem.value == '') txtElem.value = strUserName;
}
function PasswordBlur(txtElem, strPassword) {
if (txtElem.value == '') txtElem.value = strPassword;
}
function UserNameFocus(txtElem, strUserName) {
if (txtElem.value == strUserName) txtElem.value = '';
}
function PasswordFocus(txtElem, strPassword) {
if (txtElem.value == strPassword) txtElem.value = '';
}