I have this html code
<html>
<head>
<title>JQuery Problem 2</title>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript" src="problem2.js"></script>
</head>
<body>
<div id="game">
<form onsubmit="return false">
<p>
Guess:
<input type="text"/>
<input type="submit" value="Go"/>
</p>
<p>
<strong>Number of guesses:</strong>
<span>0</span>
</p>
<p>
<strong>Last guess:</strong>
<span>None</span>
</p>
<table border="1" cellpadding="4" cellspacing="1" style="width: 400px">
<tr>
<th>Guess</th>
<th>Result</th>
</tr>
</table>
</form>
</div>
</body>
</html>
When the user enters his value i want to retrieve the numerical value that they entered in the textbox, with jQuery, how would i go about doing that?
You can select checkboxes using the :text selector but generally I would recommend using an ID or class, as appropriate.
The value of a text box can be obtained using val().
For example, this function listens for change events on all text boxes and alerts the new value:
$(":text").change(function() {
alert($(this).val());
});
First I would add either a class or an ID to your input. Once you do that, you can retrieve it very easily like so:
var value = $('.yourClass').val();
or if you give it an ID:
var value = $('#yourID').val();
For the unique control in the page, to assign an ID is a good practice.
For looped element such as table list, use position selector is better.
Related
I am creating a form where the user can add fields one after the other. For each field I am setting a "remove" button. Each field is in a table, so I give a random id to the table, and pass this id to a removing function doing: $(random-id).remove().
The strange thing is that jQuery is removing all of the tables created by the user, as if the id is not taken into account
Why that can be?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
function delete_field(id)
{
$("#"+id+"").remove();
}
function add_form_field()
{
id = Math.random();
html = '<table id='+id+'>\
<tr><td>Label </td></tr>\
</table>\
\
<button onclick=delete_field('+id+')>remove</button>';
$("form").append(html);
}
</script>
</head>
<body>
<form>
</form>
<button onclick=add_form_field()> Add a field </button>
</body>
</html>
Don't use Math.random, rather increment a number and create ID like: #tab_NN.
Add an ID to your Form Element id=myForm
Delegate click events to dynamically generated delete buttons using .on()
While removing the table that matched the button data-* attribute, delete the button too using .add( this ) (where this stays for the clicked button)
var id = 0;
function delete_field(event){
event.preventDefault();
$("#tab_"+ $(this).data("remove")).add(this).remove();
}
function add_form_field(){
id += 1;
var html = '<table id="tab_'+ id +'">'+
'<tr><td>Label</td></tr>'+
'</table>'+
'<button data-remove="'+id+'" class="remove">remove</button>';
$("#myForm").append(html);
}
$('#addField').on('click', add_form_field);
$('#myForm').on('click', '.remove', delete_field);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm"></form>
<button id="addField"> Add a field </button>
The code above allows you to have changes in the future markup cause it targets a specific ID, but in case your DELETE buttons will always be exactly after table than you can do it without assigning ID's, by simply using .prev("table"):
http://jsbin.com/wuqati/1/edit
function delete_field(event){
event.preventDefault();
$(this).prev("table").add(this).remove();
}
function add_form_field(){
var html = '<table>'+
'<tr><td>Label</td></tr>'+
'</table>'+
'<button class="remove">remove</button>';
$("#myForm").append(html);
}
$('#addField').on('click', add_form_field);
$('#myForm').on('click', '.remove', delete_field);
Math.random() produces a floating point number less than 1 which is invalid for an id. You can use a global variable to keep count of the rows created. Keep in mind that a CSS ID can not start with a digit. So append the number to a string before using it as an ID.
<script>
function delete_field(id)
{
$("#"+id+"").remove();
}
tableID = 1;
function add_form_field()
{
id = 'table-'+tableID;
html = '<table id='+id+'>\
<tr><td>Label </td></tr>\
</table>\
\
<button onclick=delete_field('+id+')>remove</button>';
$("form").append(html);
tableID++;
}
</script>
Why not simplify this by doing something like below.
$(".remover").click(function() {
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" placeholder="input One"/> <input type="button" class="remover" value="remove" />
</td> </tr>
<tr>
<td>
<input type="text" placeholder="input Two"/> <input type="button" class="remover" value="remove" />
</td> </tr>
<tr>
<td>
<input type="text" placeholder="input Three"/> <input type="button" class="remover" value="remove" />
</td> </tr>
</table>
forprice.innerHTML=document.forms[0].elements[2].value;
i understant that the forprice variable is changed (basically the left side of the equation) but what i dont understand is the forms[0] part
and the elements [2]. value part-my understanding of the elements. value portion is that it takes whatever the value is of the element that is in the second position, or possibly the second elements in the form. below is the code for the whole page
-thanks
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var imgs=new Array();
imgs[0]=new Image(400,400);
imgs[1]=new Image(400,400);
imgs[2]=new Image(400,400);
imgs[3]=new Image(400,400);
imgs[4]=new Image(400,400);
imgs[0].src="m&p45blackwithcase.jpg";
//the above image does not load for some reason... i have tried changing the array order to included this first,
imgs[1].src="m&p45optimized.jpg";
imgs[2].src="m&p45blackoptimized.jpg";
//eliminated image due to corruption
imgs[3].src="taurus24-7package.jpg";
imgs[4].src="taurus689.jpg";
var imgs2=new Array();
imgs2[0]=new Image(400,400);
imgs2[1]=new Image(400,400);
imgs2[2]=new Image(400,400);
imgs2[0].src="ammochart.jpg";
imgs2[1].src="HANDGUN_AMMUNITION_CHART.jpg";
imgs2[2].src="rifle-ammo-chart-optimized.jpg";
</script>
<script>
var i=0;
function forward(){
// alert ("function");
i++;
if(i==5){
i=0;}
document.main.src=imgs[i].src;
}
function backward (){
i--;
if(i==-1){
i=4;}
document.main.src=imgs[i].src;
}
function update(form){
var imgvalue=document.getElementById("imgslider");
whichimg=imgvalue.value;
document.main.src=imgs[whichimg].src;}
function selectthis (form){
var cntr;
// alert ("function");
cntr=form.ammodd.selectedIndex-1;
document.main2.src=imgs2[cntr].src;
/*
//forprice=document.getElementById("desc");
//forprice.innerHTML=document.forms[0].elements[2].value;
removed because it's not needed
var imgvalue2=document.getElementById("secondary");
whichimg=imgvalue2.value;
document.secondary.src=imgs2[whichimg].src;
*/
}
var forprice;
var cntr;
function selectthis (form){
cntr=form.gundd.selectedIndex-1;
document.main.src=imgs[cntr].src;
forprice=document.getElementById("price");
forprice.innerHTML=document.forms[0].elements[2].value;
}
</script>
</head>
<body>
<div align="center">
<table width="600" border="0">
<caption>
<h1>Firearms Deluxe Emporium Superstore Outlet Market Discount Megacenter</h1>
</caption>
<tbody>
<tr>
<td><div align="center">Home</div></td>
<td><div align="center">Products</div></td>
<td><div align="center">Checkout</div></td>
</tr>
</tbody>
</table>
<h1> </h1>
<p><img src="m&p45blackwithcase.jpg" name="main" width="640" height="480" id="main"/></p>
<form id="form1" name="form1" method="post" action ="">
<p>Just </p>
<select name ="gundd" onchange="selectthis(this.form)">
<option value ="#" selected="selected"> Choose one </option>
<option value ="400.00">Psychedelic View 1</option>
<option value ="450.00">Psychedelic View 2</option>
<option value ="500.00">Psychedelic View 3</option>
<option value ="871.00">Psychedelic View 4</option>
</select>
<table width="400" border="4">
<tr>
<td align="right"> <input type="button" name="backup" id="backup" value="back" onclick="backward()"/></td>
<td align ="left"> <input type="button" name="forwardon" id="forwardon" value="forward" onClick="forward()"/></td>
</tr>
<tr>
<td colspan="2" align="center"> <input type="range" id="imgslider" name="imgslider" min="0" max="4" value="0" step="1" onchange="update(this.form)"></td>
</tr>
</table>
</form>
<form id="form2" name="form2" method="post" action ="">
<p> </p>
<p> </p>
<p> </p>
<p><img src="bullitsassorted-optimized.jpg" id="main2" name ="main2" width="620" height="465" alt=""/></p>
<p> We have all types of rounds available. </p>
<p>Whatever your needs are, we can fill them. </p>
<p>
<select name="ammodd" onchange="selectthis(this.form)">
<option selected="#">We even have amunition</option>
<option>Rifle Rounds</option>
<option>Handgun Rounds</option>
<option>Uses</option>
</select>
</form>
</div>
</body>
</html>
JavaScript is effectively looking for the FIRST (0) `' object, then the value assigned to the third element within the form.
The second element is the select named gundd. The value would be which option is selected. # if nothing selected.
Starting with the right side.
document.forms[0]
document.form gives you an array of all forms in the DOM. You can think of the DOM simply as a collection of all elements on the html page. forms[0] means you will get the first element in the array. This comes out to being the form with name="form1". So..
document.forms[0]
//points to
<form name="form1">...</form>
Next comes
document.forms[0].elements[2]
In a similar respect, this takes the form we are dealing with, and gives an array of all the elements in the form. These are not to be confused with children. It only gives the form elements like input, select. Not p or h1 even if they are inside the form. the [2] means we get the third element in the array. It looks like that would be the input with name="forwardon". Note, the option elements do not count since they are all considered part of the select.
Finally
document.forms[0].elements[2].value;
The .value simply means the value of the element we just pointed to. That would be "forward".
To put it all together.
forprice.innerHTML=document.forms[0].elements[2].value;
We are changing the dom element assigned to the variable "forprice" so that it's html contents will equal "forward". That is what the .innerHTML does - alter the contents between the tags of an html element. It appears forprice is set to an element with the id="desc" which i cannot find, but it would hypothetically look like this after the javascript.
<p id="desc">forward</p>
I want to hide my form when I click on the submit button. My code is as follows:
<script type="text/javascript">
function hide() {
document.getElementById("test").style.display = "hidden";
}
</script>
<form method="post" id="test">
<table width="60%" border="0" cellspacing="2" cellpadding="2">
<tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold"
align="center">
<td>Ample Id</td>
<td>Find</td>
</tr>
<tr align="center" bgcolor="#E8F8FF" style="color:#006">
<td>
<input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>"
/>
</td>
<td>
<input type="image" src="../images/btnFind.png" id="find" name="find"
onclick="javascript:hide();" />
</td>
</tr>
</table>
</form>
But when I click on the "Find" button, that particular form is not being hidden.
It should be either
document.getElementById("test").style.display = "none";
or
document.getElementById("test").style.visibility = "hidden";
Second option will display some blank space where the form was initially present , where as the first option doesn't
Set CSS display property to none.
document.getElementById("test").style.display = "none";
Also, you do not need javascript: for the onclick attribute.
<input type="image" src="../images/btnFind.png" id="find" name="find"
onclick="hide();" />
Finally, make sure you do not have multiple elements with the same ID.
If your form goes nowhere, Phil suggested that you should prevent submission of the form. Simply return false in the onsubmit handler.
<form method="post" id="test" onsubmit="return false;">
If you want the form to post, but hide the div on subsequent page load, you will have to use server-side code to hide the element:
<script type="text/javascript">
function hide() {
document.getElementById("test").style.display = "none";
}
window.onload = function() {
// if form was submitted, PHP will print the below,
// which runs function hide() on page load
<?= ($_POST['ampid'] != '') ? 'hide();' : '' ?>
}
</script>
Using jQuery:
$('#test').hide();
Using Javascript:
document.getElementById("test").style.display="none";
Threw an error "Cannot set property 'display' of undefined"
So, fix for this would be:
document.getElementById("test").style="display:none";
where your html code will look like this:
<div style="display:inline-block" id="test"></div>
Replace hidden with none. See MDN reference.
There are two ways of doing this.
Most of the answers have correctly pointed out that style.display has no value called "hidden". It should be none.
If you want to use "hidden" the syntax should be as follows.
object.style.visibility="hidden"
The difference between the two is the visibility="hidden" property will only hide the contents of you element but retain it position on the page. Whereas the display ="none" will hide your complete element and the rest of the elements on the page will fill that void created by it.
Check this illustration
its a block element, and you need to use none
document.getElementById("test").style.display="none"
hidden is used for visibility
Maybe you can add a class like 'hide'.
Follow the example here : https://developer.mozilla.org/fr/docs/Web/API/Element/classList.
document.getElementById("test").classList.add("anotherclass");
you need to use display = none
value hidden is connected with attributet called visibility
so your code should look like this
<script type="text/javascript">
function hide(){
document.getElementById("test").style.display="none";
}
</script>
you can use something like this....div container
<script type="text/javascript">
function hide(){
document.getElementById("test").innerHTML.style.display="none";
}
</script>
<div id="test">
<form method="post" >
<table width="60%" border="0" cellspacing="2" cellpadding="2" >
<tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
<td>Ample Id</td>
<td>Find</td>
</tr>
<tr align="center" bgcolor="#E8F8FF" style="color:#006" >
<td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
<td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>
</tr>
</table>
</form>
</div>
Through JavaScript
document.getElementById("test").style.display="none";
Through Jquery
$('#test').hide();
this should be it try it.
document.getElementById("test").style.display="none";
I'm very new to JavaScript and trying to mimic an example in a book I'm reading. I would like to take what is input to a HTML element and send the data to a element using .innerHTML. I don't know what is wrong.
<!DOCTYPE html>
<html>
<head>
<title>JS Form</title>
</head>
<body>
<form id="date">
<table>
<tr><td><input type="text" name="user" placeholder="Please input name" onchange="greeting();"></td>
</tr>
<tr><td><span id="hello"></span></td>
</tr>
</table>
</form>
<script type="text/javascript">
function greeting() {
var user = document.date.user.value;
var hello = document.getElementById("hello");
hello.innerHTML = "How are you " + user;
}
</script>
</body>
</html>
Add name="date" to your form tag like below. Else document.date.user.value will not work.
<form id="date" name="date">
Another way to get around the issue, is accessing the date property of the window object.
window.date.user.value;
This is possible because you've set an id on the form.
Or you might consider accessing the form using its id and then get user value as follows:
var user = document.getElementById("date").user.value;
For simplification, and depending on your browser, you could use document.querySelector. Take a look at this very helpful SO post:
JavaScript: how to get value of text input field?
you should do this first:
var user= document.getElementsByName("user");
var hello = document.getElementById("hello");
hello.innerHTML = "How are you " + user[0].value;
how can I take the value of a query string and place it into an input box? Currently I have:
<input type="text" name="spouse" id="spouse" value="<script type="text/javascript">
document.write("Name: " + Request.QueryString("spouse"));
</script>"/>
But that only takes the script take and all of its contents and places it into the input box.
I would like to be able to take my query string that is coming from this code:
<tr >
<td><input type="text" name="n1" value="Duck, Donald" /></td>
<td><input type="text" name="n2" value="Daisy" /></td>
<td><input type="button" value="Show" title="Show"
onclick="location.href='example123.html?name=' + escape(this.form.n1.value)+ '&spouse=' + escape(this.form.n2.value);" />
</td>
and have the value for name or spouse appear inside of an input box. What is the proper way to place a value into an input box from a query string?
Request.QueryString is not a native JavaScript function. Use the document.location object and parse out the value you want.
Perhaps use the onload function to perform the action you need. This calls your function once the document has been fully loaded and so you know all tags in the html will exist at this point and be can be referenced properly.
eg.
<html>
<head>
<title>Value Setting</title>
<script type="text/javascript">
window.onload = (function() {
document.getElementById('spouse').value = "one way";
document.forms[0].elements[1].value = "another way";
/* note elements refers to only input children */
});
</script>
</head>
<body>
<form id="myform">
<div>
<input id="first-field" value="first-field" onchange="this.value += ' an example';"/>
</div>
<div>
<p>
<input id="spouse" value="spouse"/>
</p>
</div>
</form>
</body>
</html>
You can't embed elements in attributes as that isn't valid html. Though some attributes can get evaluated as javascript. Namely attributes such as action, onchange, onclick and so on.