I need to add product info from inputs to table by using jQuery library. I am trying for quite some time now, but I don't get anywhere. First I need to enter data to inputs, select appropriate radio button and than validate input fields. If there are no errors, product info should be added to table. I tried with the following code: jsFiddle
Nothing works as intended tho. What am I doing wrong?
JS code:
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function () {
//Check if any of requested inputs is empty
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").val('Missing product name');
break;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").val('Missing price');
break;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
//Check radio buttons and assign values
if ($('input[value = "true"]'.is(':checked')) {
onStack = "Product available";
} else if ('input[value = "false"]'.is(':checked') {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>$productName</td><td>$price</td><td>$onStack</td></tr>");
});
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<body>
<form method="" action="">
<input type="text" id="name" placeholder="Product name" />
<br />
<input type="text" id="price" placeholder="Price" />
<br/>
<input type="radio" name="stack" value="true">Product available
<br />
<input type="radio" name="stack" value="false">Product not available
<br />
<input type="submit" value="Submit">
</form>
<div id="errors"></div>
<br />
<table border="1">
<tr>
<th>Product name</th>
<th>Price</th>
<th>Stack</th>
</tr>
</table>
<div id="sumOnStack">Sum of available products</div>
<div id="SumNotOnStack">Sum of unavailable products</div>
<input type="button" id="resetForm" value="Reset form" />
<br />
</body>
</html>
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function ( e) {
//Check if any of requested inputs is empty
$("#errors").html('');
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").html('Missing product name');
return false;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").html('Missing price');
return false;
} else if($('input[name="stack"]:checked').length == 0) {
$("#errors").html('Missing product availibility');
return false;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
var stack = $('input[name="stack"]:checked');
console.log( $(stack).val() );
//Check radio buttons and assign values
if ($(stack).val() == 'true') {
onStack = "Product available";
} else {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>"+productName+"</td><td>"+ price +"</td><td>"+ onStack +"</td></tr>");
return false;
});
});
Please try this. Hope above code will help u.
Related
I'm having trouble figuring out how to do this, and well, need help.
I'm trying to put my information into an array that's going to be shown and always be able to grow. I need help deleting specific entries into it, either by searching for one or by pointing a mouse and deleting it,
Is there any nice easy way to do it?
<!doctype html>
<html lang="sv">
<body>
<head>
<meta charset="UTF-8">
</title>
</head>
<body>
<input type="text" placeholder="Förnamn" id="name" autofocus>
<input type="date" id="pnummer" autofocus>
<input type="text" placeholder="Efternamn" id="enamn" autofocus>
<input type="button" value="mata in" onclick="register()">
<input type="button" value="visa" onclick="show()">
<script type="text/javascript">
array=[]
function register()
{
var fnamn = document.getElementById("name").value;
var enamn = document.getElementById("enamn").value;
var pnummer = document.getElementById("pnummer").value;
var p1 = new Person(fnamn,pnummer,enamn);
array.push(p1);
}
function Person(fnamn, pnummer, enamn)
{
this.fnamn=fnamn;
this.pnummer=pnummer;
this.enamn=enamn;
this.visa=function()
{
var panel ="Förnamn:"+" "+this.fnamn+" "+"Efternamn:"+" "+this.enamn+" "+"Personnummer:"+" "+this.pnummer+"<br>";
return panel;
}
}
function show(){
var showperson=document.getElementById("new");
showperson.innerHTML="";
var i=0;
while (array.length>i)
{
showperson.innerHTML+=array[i].visa()
i++;
}
}
</script>
<p id="new"></p>
<div id="panel"></div>
</body>
</html>
I am not 100% sure what you're trying to do or what some of those words mean but is this what you're trying to do?
var peopleTracker = {};
var peopleCounter = 0;
function addPerson()
{
// get the values
var firstName = document.getElementById("firstName").value.trim();
var lastName = document.getElementById("lastName").value.trim();
var birthday = document.getElementById("birthday").value.trim();
// make sure none are blank
if(firstName == "" || lastName == "" || birthday == "") return;
// give each person an ID so we can remove them later
var personID = ++peopleCounter;
peopleTracker[personID] = {
"firstName" : firstName,
"lastName" : lastName,
"birthday" : birthday
};
// add the person to the table
var row = document.getElementById("peopleList").insertRow();
row.insertCell().innerText = firstName;
row.insertCell().innerText = lastName;
row.insertCell().innerText = birthday;
row.insertCell().innerHTML = 'remove';
}
// delete a user from the tracker and remove the row
function removePerson(row, personID)
{
delete peopleTracker[personID];
row.parentNode.removeChild(row);
}
<!doctype html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>the dingo ate my baby</title>
</head>
<body>
<input type="text" placeholder="First Name" id="firstName" autofocus>
<input type="text" placeholder="Sur Name" id="lastName" autofocus>
<input type="date" id="birthday" autofocus>
<input type="button" value="Add Person" onclick="addPerson()">
<br /><br />
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Sur Name</th>
<th>Birthday</th>
<th>Action</th>
</tr>
</thead>
<tbody id="peopleList"></tbody>
</table>
</body>
</html>
A few thoughts:
If you're going to use an array to delete then you're going to need to use some unique ID to be able to find the person you want to delete. You cannot use the array index because that will change as you remove people from the array.
By using an object to store the users you can delete by using a unique ID that changes for each user added.
I jQuery is an option, you could find the index of your clicked <div> and delete the element with something like the following function:
$( "div.someIdYouGiveIt" ).click(function() {
var index = $( "div.someClassYouGiveIt" ).index( this );
array.splice(index, 1);
});
I have a PHP snippet that display the table row dynamically. Every row I there's a radio button with "Yes" and "No" option.
I created a JS function, when the user choose an option, there's a pop-box will be displayed.
If the user choose "Yes" option in the radio button and click "Ok" in the pop-box, the table row will be disabled even the radio button will be disable too. And the chosen option will be save in MYSQL.
How to save the chosen option in MySQL?
My JS snippet of disabling a row is not working. How to fix this?
PHP:
echo '<td id="resumeFile">Download Resume</td>';
echo '<td id="radioOption">
<label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes" name="processedOption" value="Yes" onclick="proccessedCheck()"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo" name="processedOption" value="No" onclick="proccessedCheck()"/></td>';
JS:
function proccessedCheck(){
var checked = null;
var inputs = document.getElementsByName('processedOption');
for (var i = 0; i < inputs.length; i++){
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked == null){
return false;
} else if (checked == true){
document.getElementById("resumeFile").disabled = true;
document.getElementById("radioOption").disabled = true;
document.getElementById("resumeFile").title = "This option has been disabled.";
} else {
return confirm('You have chosen '+ checked.value + ', is this correct?');
}
}
Ok so if you are echo'ing the whole table from PHP just preset the parameters into the table
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script>
function proccessedCheck(id,answer) {
if (confirm('You have chosen '+ id +': '+ answer + ', is this correct?')) {
$("#processedOptionYes"+id).attr('disabled',true);
$("#processedOptionNo"+id).attr('disabled',true);
var withlink = $("#resumeFile"+id).html();
var withoutlink = $(withlink).html();
$("#resumeFile"+id).html("").append(withoutlink);
$("#input1".val(id);
$("#input2".val(answer);
$("#myform").submit();
}
}
</script>
<!-- EDIT: hidden form to submit -->
<form id="myform" method="POST" action="savedb.php">
<input type="hidden" id="input1" name="id" />
<input type="hidden" id="input2" name="answer" />
</form>
<table>
<tr>
<?php
$dir="";
$file="";
$id = 0;
//foreach($array as $row) {
$id++;
echo '<td id="resumeFile'.$id.'">Download Resume</td>';
echo '<td id="radioOption>
<label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes'.$id.'" name="processedOption" value="Yes" onclick="proccessedCheck('.$id.',\'Yes\')"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo'.$id.'" name="processedOption" value="No" onclick="proccessedCheck('.$id.',\'No\')"/></td>';
//}
?>
</tr>
</table>
</body>
</html>
Contents of savedb.php, this doesn't have to be a seperate file
<?php
// Check if my post array arrived, comment this line when u done
echo "<pre>";print_r($_REQUEST);echo "</pre>"; die();
// Connect to DB
// Build SQL insert string with $_REQUEST['id'] as the primary key
?>
For starters, try replacing:
document.getElementById("resumeFile").disabled = true;
document.getElementById("radioOption").disabled = true;
with:
document.getElementById("processedOptionYes").disabled = true;
document.getElementById("processedOptionNo").disabled = true;
I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>
I'm making a recipe calculator for my coursework. I have reached the stage where it will correctly validate everything and make a new row in a table. Sadly in the if statement within the recipe function, it always goes true for isNaN? No matter what I put? Can anyone help me with this?
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<script type="text/javascript">
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var ingredientcount = 0
// The save function
function save(){
var verified = true;
while(verified){
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if(serves === "" || name === "" || isNaN(serves)=== true)
{
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
}
else{
alert("sucess!");
// array(ingredient,amount,unit,name,serves)
return;
}
}
}
// The function to valiate the data and manage everything
function recipe(){
if(ingredient === ""|| amount === "" || unit === "Select Unit"){
alert("You must fill in all fields.")
}
else if(isNaN(amount)){
alert("You have to enter a number in the amount field")
}
else{
alert("hey!")
alert(recipe[1][2] + recipe[1][1])
var totalamount = amount + " "+ unit
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
ingredientcount ++;
alert(ingredientcount);
}
}
</script>
</head>
<body>
<h1>Recipe Name</h1>
<h2>Serves many people </h2>
<table border="1" id="table" >
<tr>
<td>
<input type="text" id="ingredient" placeholder="Enter an Ingredient">
</td>
<td>
<input type="text" id="number" placeholder="Enter an amount">
<select id="unit">
<option>Select Unit</option>
<option>Grams</option>
<option>Mililitres</option>
<option>Number</option>
</select>
</td>
<td>
<button type="button" onclick="recipe()">Add</button>
<button type="button" onclick="save()">Save</button>
</td>
</tr>
<th>Ingredient</th>
<th>Amount</th>
<th> </th>
</table>
</body>
</html>
The problem is that you are setting the values of ingredient, amount, and unit when the page loads, not when the Add button is pushed. You need to move those assignments to the recipe() function.
So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);