Duplicate Forms with Jquery - javascript

i found on the Internet a plugin and add some new lines to form this:
(function($){
$countForms = 1;
$countFormsA = 1;
$.fn.addForms = function(idform){
var myform = "<table>"+
" <tr>"+
" <td>Field A ("+$countForms+"):</td>"+
" <td><input type='text' name='fielda["+$countForms+"]'></td>"+
" <td>Field B ("+$countForms+"):</td>"+
" <td><textarea name='fieldb["+$countForms+"]'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
var myform2 = "<table>"+
" <tr>"+
" <td>Field C</td>"+
" <td><input type='text' name='fieldc["+$countFormsA+"]'></td>"+
" <td>Field D ("+$countFormsA+"):</td>"+
" <td><textarea name='fieldd["+$countFormsA+"]'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
if(idform=='mybutton'){
alert(idform);
myform = $("<div>"+myform+"</div>");
$("button", $(myform)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform);
$countForms++;
}
else{
if(idform=='mybutton1'){
alert(idform);
myform2 = $("<div>"+myform2+"</div>");
$("button", $(myform2)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform2);
$countFormsA++;
}
}
};
})(jQuery);
$(function(){
$("#mybutton1").bind("click", function(){
var idform=this.id;
if($countFormsA<3){
$("#container1").addForms(idform);
}
});
});
$(function(){
$("#mybutton").bind("click", function(){
var idform=this.id;
if($countForms<3){
$("#container").addForms(idform);
}
});
});
However i'm having a problem. If i click "add form" everything works, but when i click "add form 1" the new form is added but after 1 second it disappears. Any hint how can i solve this? Thank you!
The html code:
<button id="mybutton">add form</button>
<div id="container"><div>
<form method="post" name="b" >
<table>
<tr>
<td>Field A</td>
<td><input type='text' name='dadoA'></td>
<td>Field B</td>
<td><textarea name="dadoB"></textarea></td>
<td><button>remove</button></td>
</tr>
</table></div></div>
<div align="center">
<p><input type="submit" value="Registar" name="registar"></p>
</div>
<!-- -->
<button id="mybutton1">add form1</button>
<div id="container1"><div>
<form method="post" name="a" >
<table>
<tr>
<td>Field A</td>
<td><input type='text' name='dadoA'></td>
<td>Field B</td>
<td><textarea name="dadoB"></textarea></td>
<td><button>remove</button></td>
</tr>
</table></div></div>
<div align="center">
<p><input type="submit" value="Registar1" name="registar1"></p>
</div>

The form will disappear because the page is being refreshed by that button's default behaviour.
You will need to prevent that behaviour in your click binding. I would suggest passing the event object through and using preventDefault() ie:
$("#mybutton1").bind("click", function(e){
e.preventDefault();
var idform=this.id;
if($countFormsA<3){
$("#container1").addForms(idform);
}
});

Related

"input type="submit"" not displaying as a button

I am trying to create a web-based quiz application where the quiz is inputted through a form and then inputted into a text file. this will then be read from the text file to the user separately. My submit button is not working however, have i laid it out wrong?
The idea is to then read the text file line by line calling on values define by these lines, and displaying the options in radio format on a seperate webpage. Also, i wish to add a new button called "add question" which adds the question and 3 answer input texts to the bottom of the form, making it responsive to the user. Would i have to make the whole form a function and call on it?
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile(“using theseee / this.txt ", True);
var year = document.getElementById(‘year’);
var class = document.getElementById(‘class’);
var topic = document.getElementById(‘topic’);
var title = document.getElementById(‘title’);
var question = document.getElementById(‘question’);
var option1 = document.getElementById(‘answer1’);
var option2 = document.getElementById(‘answer2’);
var option3 = document.getElementById(‘answer3’);
s.writeline(“Title: " + title);
s.writeline(“Question: " + question);
s.writeline(“Option1: " + answer1);
s.writeline(“Option2: " + answer2);
s.writeline(“Option3: " + answer3);
s.writeline("-----------------------------"); s.Close();
}
<html>
<head>
<title>Quiz Form</title>
<link rel=“stylesheet” href=“TRYstyle.css”>
</head>
<body>
<h3>Quiz form</h3>
<table>
<form onSubmit=“WriteToFile(this.txt)”>
<tr>
<td>Title</td>
<td><input type=“text” placeholder=“Title” name=“title” id=“title” maxlength=“200”/></td>
</tr>
<tr>
<td>Question</td>
<td><input type=“text” placeholder=“Question” name=“question” id=“question” maxlength=“200”/></td>
</tr>
<tr>
<td>Answer</td>
<td><input type=“text” placeholder=“Answer” name=“answer1” id=“answer1” maxlength=“200”/></td>
</tr>
<tr>
<td>Answer</td>
<td><input type=“text” placeholder=“Answer” name=“answer2” id=“answer2” maxlength=“200”/></td>
</tr>
<tr>
<td>Answer</td>
<td><input type=“text” placeholder=“Answer” name=“answer3” id=“answer3” maxlength=“200”/></td>
</tr>
<tr>
<input type=“submit” value=“Submit”>
</tr>
</form>
</table>
</body>
</html>
Your HTML is invalid.
A form can't be a child of a table element, and an input can't be a child of a table row element.
Only table cells can be children of a table row.
Additionally, you can't use “ (LEFT DOUBLE QUOTATION MARK) to delimit attribute values. Only " (QUOTATION MARK) or ' (APOSTROPHE ).
Use a validator.
Aside: Once you solve that problem you will discover that Scripting.FileSystemObject is not made available to web browsers. You can't write to arbitrary files with browser-side JS.
Your doublequotes are wrong.
This is how it is:
<input type=“submit” value=“Submit”>
This is how it needs to be:
<input type="submit" value="Submit">
Because of that doublequotes, type is not recognised and by default input type is text. Thats why you are having that problem.
You had multiple problems.
First the use the correct quotes helps a lot of issues.
Place your submit button in a td element so it won't be placed directly into a row.
You used class as a variable name in your javascript which is not allowed.
function WriteToFile(passForm) {
//No Idea what this is. Wont work in snippet
//set fso = CreateObject("Scripting.FileSystemObject");
//set s = fso.CreateTextFile(“using theseee / this.txt ", True);
//use the correct quotes
var year = document.getElementById('year');
//it's not allowed to use class as a variable
var classEl = document.getElementById('class');
var topic = document.getElementById('topic');
var title = document.getElementById('title');
var question = document.getElementById('question');
var option1 = document.getElementById('answer1');
var option2 = document.getElementById('answer2');
var option3 = document.getElementById('answer3');
//use the correct quotes
console.log("Title: " + title);
console.log("Question: " + question);
console.log("Option1: " + answer1);
console.log("Option2: " + answer2);
console.log("Option3: " + answer3);
console.log("-----------------------------"); s.Close();
}
<html>
<head>
<title>Quiz Form</title>
<link rel=“stylesheet” href=“TRYstyle.css”>
</head>
<body>
<h3>Quiz form</h3>
<table>
<form onSubmit="WriteToFile(this.txt)">
<tr>
<td>Title</td>
<td><input type="text" placeholder="Title" name="title" id="title" maxlength="200"/></td>
</tr>
<tr>
<td>Question</td>
<td><input type="text" placeholder="Question" name="question" id="question" maxlength="200"/></td>
</tr>
<tr>
<td>Answer</td>
<td><input type="text" placeholder="Answer" name="answer1" id="answer1" maxlength="200"/></td>
</tr>
<tr>
<td>Answer</td>
<td><input type="text" placeholder="Answer" name="answer2" id="answer2" maxlength="200"/></td>
</tr>
<tr>
<td>Answer</td>
<td><input type="text" placeholder="Answer" name="answer3" id="answer3" maxlength="200"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit">
</td>
</tr>
</form>
</table>
</body>
</html>

How to access HTML array object in javascript?

sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}

onsubmit event not working in IE11

I have a form that uses the onsubmit event.
Tested in MS Blade, Chrome Version 67, Firefox Version 60 and the event works as expected.
This means a dialogue box appears and asks "do you wish to proceed with the order and lists the item and value". With options to select "ok" or "cancel".
Tested in IE11 and the event fires but goes directly to the cancel option and reloads the page.
<form onsubmit="confirmBox()" action="#" name="order_form" id="order_form">
<table>
<tr>
<td>Price</td>
<td><div id="divPriceObj"></div></td>
<td><input type="hidden" name="price" id="price" value=""></td>
</tr>
<tr>
<td><label>Quantity</label></td>
<td><input type="number" name="quantity" id="quantity" min="1" value="1"></td>
<td>REQUIRED FIELD</td>
<td><input type="hidden" name="description" id="description" value=""></td>
</tr>
<tr>
<td><label>Total Price</label></td>
<td><div id="totalPrice"></div></td>
</tr>
<tr>
<td><button type="button" onclick="resetQuantity()">Clear</button></td>
<td><button type="button" onclick="calculateTotal()">Calculate Total</button></td>
<td><input type="submit" name="submit" id="submit" value="Submit" /></td>
</tr>
</table>
</form>
The Javascript involved is
function confirmBox() {
var itemDesc = setDesc(getUrlVars()["description"]);
var itemPrice = document.forms["order_form"]["price"].value;
var itemQuantity = document.forms["order_form"]["quantity"].value;
var itemTotal = itemPrice * itemQuantity;
//check if form data is valid still
if (validateForm(price, quantity)) {
var x = document.forms["order_form"]["price"].value;
var y = document.forms["order_form"]["quantity"].value;
var z = getUrlVars()["desc"];
if (confirm('Do you wish to Proceed with the order of '
+ itemQuantity
+ ' ' + itemDesc
+ ' valued at $'
+ itemTotal + '?')) {
close();
} else {
resetQuantity();
}
} else {
//do nothing
//close();
}
}
I have not been able to fix this bug, does anyone have a solution?

JQuery can't get input value from dynamically created field

Receiving value from static field when keyup based on input field class(.inputclass) method, but once add field dynamically its not get the value.
Below the sample code, Please help.
$(function(){
$(document).ready(function(){
$(".inputclass").keyup(function() {
alert($(this).val());
});
});
});
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
<tr>
<td>Field 1</td>
<td><input type="text" class="inputclass" /></td>
</tr>
<script>
var counter =1;
$(function(){
$('#addNew').click(function(){
counter += 1;
$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
});
});
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form>
This is because when you assigned the event handler, it only assigned to the existing elements at the time.
Delegate to the document:
$(document).on('keyup', '.inputclass', function(){
alert($(this).val())
});
When you delegate to a parent or the document, you are using the event that bubbles up and so it doesn't matter if there are dynamic elements.
$(function(){
$(document).ready(function(){
$(document).on('keyup', '.inputclass', function(){
alert($(this).val());
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
<tr>
<td>Field 1</td>
<td><input type="text" class="inputclass" /></td>
</tr>
<script>
var counter =1;
$(function(){
$('#addNew').click(function(){
counter += 1;
$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
});
});
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form>

window.location.href still not working after cancelling form submission

I have an login form
<div id='login_form'>
<table>
<tr>
<td>Username:</td>
<td><input size=25 type='text' id='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input size=25 type='password' id='password'></td>
</tr>
<tr>
<td colspan='2' align='right'>
<input type='button' id='login' value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>
</td>
</tr>
</table>
</div>
then I have javaScript
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username === "123" && input_password === "456"){
alert("Correct username & password");
window.location.href="../../result.html";
return false;
}
But when I received the alert "Correct username & password", the page was not redirected to result.html. And I checked, "../../result.html" exists.
I found some people said the submission should be cancelled, so I deleted form and changed the " type = "submit" " to " type = "button" "for Login button, but it was not working.
And there is also another method, add "return false" after " window.location.href="../../result.html" ", but it was not working as well.
Any one has any idea????
Thanks in advance!
Username/password checking should be done on the backend (Java, PHP, Node, .NET)
Your form should be in a form tag though. The checking should be done in the onsubmit callback:
<script>
function authenticate(){
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username==="123"&&input_password==="456"){
alert("Correct username & password");
window.location.href = "../../result.html";
}
else {
// Error
}
return false;
}
</script>
<form onsubmit="authenticate()">
<table>
<tr>
<td>Username:</td>
<td><input size="25" type="text" id="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input size="25" type="password" id="password"></td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
<button onkeydown="normalobjKeyFunc(this)" onfocus="itemFocus(this)" onblur="itemBlur(this)">Login</button>
</td>
</tr>
</table>
</form>
Put an onclick in your button to call your javascript function..
<input type='button' id='login' onclick="authenticate()" value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>

Categories

Resources