i found this tutorial, where they explain very well how to add dynamic inputs, however, if the submit button is clicked, this does not filter the empty values from the inputs. The idea is to filter those empty values before sending them to the server, some idea?
http://www.codexworld.com/add-remove-input-fields-dynamically-using-jquery/
The code:
<?php
if(isset($_REQUEST['submit'])){
$field_values_array = $_REQUEST['field_name'];
print '<pre>';
print_r($field_values_array);
print '</pre>';
foreach($field_values_array as $value){
//your database query goes here
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add more fields using jQuery</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><img src="remove-icon.png"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
</head>
<body>
<form name="codexworld_frm" action="" method="post">
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value=""/>
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="submit" value="SUBMIT"/>
</form>
</body>
</html>
One way would be remove the empty inputs within a submit event handler
$('form[name=codexworld_frm']).submit(function(){
$(this).find('input').filter(function(){
return !this.value;
}).remove();
})
From reading your comments, you are trying to validate existing Dom elements and elements that you add dynamically and the problem is that the added elements aren't hitting your validation code?
If so, try attaching the validator using delegate instead of however you are currently doing it
http://api.jquery.com/delegate/
This allows for elements added to the Dom to behave how you expect.
Related
I know this may be a dumb question to some but I am pretty new to this and trying to learn. I have been stuck on this for days and couldn't figure it out so I came here for help. Whenever I hit the button it doesn't display my input at all. I want to make it that when the user clicks the button their input will show up in an ol list.
let form = document.getElementById("todo");
let list = document.getElementById("myList");
let input = document.getElementById("add1");
let input2 = document.getElementById("add2");
let button = document.getElementById("button");
let id = 1;
button.addEventListener("click", addToDo)
list.addEventListener("click", removeEvent)
function addToDo (e) {
let text = input.value;
let textAdd = input2.value;
let item = `<li class="del">
${text} ============= ${textAdd} <button class="del">Delete</button>`
list.insertAdjacentHTML("beforeend",item);
id++;
document.getElementById("add1").value = "";
document.getElementById("add2").value = "";
}
function removeEvent(e) {
if(e.target.classList.contains("del")) {
list.removeChild(e.target.parentElement);
list.removeChild(list);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1 id="name">Todo List</h1>
<link href="project.css" rel="stylesheet"/>
</head>
<body>
<div id="todo">
<h1>Name</h1>
<input type="text" id="add1" placeholder="Title">
<br>
<h1>Add Reminder</h1>
<input type="text" id="add2" placeholder="Notes">
<button id="button">Submit</button>
</div>
<ol id="myList">
</ol>
<script src="pro.js"></script>
</body>
</html>
There is something "special" about buttons within a form.
If your HTML looks like:
<form>
<input placeholder="enter some text">
<button>Click me</button>
</form>
Your button will submit the form and therefore reset it.
I guess you would expect the form to have some crucial properties to do so, namely 'action' and 'method' (to send the data in your inputs to some remote address - because that's the main concern of forms).
If you want your button to just be a button, use the following:
<form>
<input placeholder="enter some text">
<button type="button">Click me</button>
</form>
And you'll see: nothing happens.
I've created a StackBlitz here for you (just look at the HTML file). With type="button", more and more inputs are added to the form. If you omit this, you can see the input is added, and immediately after it, the form resets itself (sending a GET request to '/' and refreshing everything - but that's something for another question).
So, I have a form on my HTML page, and a separate button that links to the form. My question is: when the user enters a certain input (in this case a string) and clicks on the button, how do I connect the user to a different HTML page based on the corresponding user input from the form? I know I have to use javascript, but any specific code will be extremely helpful. Thanks!
ADDDED MY CODE:
<!doctype html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form id = "user-info" onSubmit="myFunction()">
<div class = "favorite-fruit">
<p>Enter your favorite fruit<br></p>
<input type="text" name="fav-fruit" id = "fruit"><br>
</div>
<div class="favorite-vegetable">
<p>Enter your favorite vegetable<br></p>
<input type="text" name="fav-vegetable" id="vegetable">
</div>
</form>
<a class = "confirm" onSubmit="myFunction()">
<button form= "user-info" type="button" name= "confirm-input">Confirm</button>
</a>
</div>
<script type="text/javascript">
function myFunction(){
var firstFruit = document.getElementById("fruit").innerHTML;
var secondVegetable = document.getElementById("vegetable").innerHTML;
var f = firstFruit;
var s = secondVegetable;
if(f.value == "Apple" && s.value == "Broccoli"){
//GO TO "appleBroccoli.html"
}
else if(f.value == "Grapes" && s.value == "Carrots"){
//GO TO "grapesCarrots.html"
}
else if(f.value == "Strawberry" && s.value == "Kale"){
//GO TO "strawberryKale.html"
}
}
</script>
</body>
</html>
It can be done by taking up the value of input tag like :-
var value = $(element).val();
Then resetting the action attribute of the form tag with the new value like :-
$(formElem).attr("action",value+".html")
I guess this would help u..
Your form, user-info doesnt have a submit button
add <input type = 'submit' name='conform'>Confirm</input> inside the form
Set action and method to the form to the corrosponding target HTML page.
<form action='..target html' method ='get'>
</form>
If the input is brocolli, you can change the form action as
document.getElementById('user-info').action = <new target>
I'm trying to check if a form type button has been pressed after i submit the form with javascript:
<script>
function DeleteIt(string){
var pattern = string.indexOf('_');
var prof_nr = string.substr(pattern+1);
var delete = confirm("Want to delete it?");
if( delete == true ){
document.forms['form'].submit();
}else{
alert('Cancel');
}
}
</script>
<form method="POST" name="form">
<input type="button" name="delete" value="Delete" id="prof_'.$row['code'].'" onclick="DeleteIt(this.id);">
</form>
if(isset($_POST['delete'])){
echo 'Pressed';
}
But it doesn't run into the condition though it has been pressed.
I can't use a submit type,because i already have one in the form , which is used for a search field.Whenever i type something and hit enter,it triggers the function,that's why i use button.
You have used so many language keywords as variable names in your code like delete, string.
You can not use reserved words of a programming language as your
variable names.
This is the working code-
<script type="text/javascript">
function DeleteIt(string1){
var pattern = string1.indexOf('_');
var prof_nr = string1.substr(pattern+1);
var delete1 = confirm("Want to delete it?");
if( delete1 == true ){
document.forms['form'].submit();
}else{
alert('Cancel');
}
}
</script>
<form method="POST" name="form">
<button name="delete" id="prof_'.$row['code'].'" onclick="DeleteIt(this.id);">delete</button>
</form>
<?php
if(isset($_POST['delete'])){
echo 'Pressed';
}
I guess a button, which is used to submit a form, will not submit its own value.
Since you do not want the form to be submitted by pressing the enter key, my idea is to add a hidden field which tells you what to do. The following code adds such a hidden field named specialAction, which is normally set to save. When the delete button is pressed, however, its value is changed to delete. In PHP, you would have to check the field's value then:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
function DeleteIt(id){
var pattern = id.indexOf('_');
var prof_nr = id.substr(pattern+1);
var deleteVar = confirm("Want to delete it?");
if( deleteVar == true ){
document.forms['form']['specialAction'].value = "delete";
document.forms['form'].submit();
}else{
alert('Cancel');
}
string
}
</script>
<form method="POST" name="form">
<input type="hidden" id="specialAction" name="specialAction" value="save">
<input type="text" name="testPurpose" value="Hit enter after focusing">
<input type="button" value="Delete" name="delete" id="prof_test" onclick="DeleteIt(this.id);">
</form>
<?php
if(isset($_POST['specialAction'])) echo $_POST['specialAction'];
?>
</body>
</html>
A side note: Do not use delete as a variable name, because it is already used as an operator. Also, you should tell the browser to interpret JavaScript using <script type="text/javascript"> and not just <script>.
Please excuse my basic query to javascript and html
I am new to javascript and html. I am trying to work with javascript on click and few other things. In below code, am trying to display a text on "onclick" function. I am using an external javascript.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" >
<script type="text/javascript" src="/home/roger/Documents/html/myScript.js"></script>
</head>
<body>
<form>
First Name: <input type="text" name="first" id="names"/><br>
Phone Number: <input type="number" name="numb" id="numb"/><br>
<button type="button" onclick="verifyText()">Click Me!</button>
</form>
</body>
</html>
Below is my code in myScript.js
function verifyText(){
document.getElementById("names").innerHTML = "Why not displaying?.";
}
If I put alert in function, pop comes out, but I am unable to figure why innerHTML is not working. Any help will be highly appreciated. Thanks.
You need to set the value, because names is an input field.
document.getElementById("names").value = "Why not displaying?.";
See: http://jsfiddle.net/zrmrx/
names is an <input>. You need to set its value, instead of innerHTML. Try this:
function verifyText(){
document.getElementById("names").value = "Must display now!";
}
Use the javascript element.setAttribute('[attr]','string') to save the user input values or input checkbox checks as part of the document innerHTML. The reset() function changes the form input back to its current Attribute setting. Javascript can dynamically change the default input value with the setAttribute therefore, change the user input default value when reset() is clicked or your code reloads it as part of a saved innerHTML.
function update_attribute() {
var obj = document.getElementById('demo');
if (obj.type == 'checkbox') {
if (obj.checked == true) {
obj.setAttribute('checked', 'checked');
} else {
obj.removeAttribute('checked');
}
}
if (obj.type == 'text') {
obj.setAttribute('value', obj.value);
}
}
<form id='myform'>
<label>Text Input</label><br>
<input type='text' id='demo'>
<br>
<br>
<button type='button' onclick='update_attribute(this)'>Change Attribute</button>
<button type='reset'>RESET</button>
</form>
If I make a form, and add an ONSUBMIT to that it gives UNDEFINED as an answer to the parent window "textarea" instead of a value from the RADIOBUTTON that is chosen. I would not want to change the javascript, because it works fine with a that has onclick with a value, but is it possible to get the to work with the same script? Or what should I do to make this work?
here is an example of my work:
index.html:
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function hello(string){
// get the current text, add a newline if not blank, and append new
// text
var anchorText = document.getElementById('myAnchor').value;
if(anchorText !== "") anchorText += '\n';
anchorText += string;
document.getElementById('myAnchor').value=anchorText;
}
</script>
<title>joubadou</title>
</head>
<body>
<form>Cart<br>
<br>
<textarea rows="10" id="myAnchor"></textarea></form>
<iframe src="radiobuttontest.html" height="300"></iframe>
</body>
</html>
radiobuttontest.html:
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
</head>
<body>
<br>
<form id="myForm" action="" method="get"
onsubmit="parent.hello()">If
you want a blue
car you can choose<br>
<br>
<input name="sex" value="Bensin" checked="checked"
type="radio">Bensin<br>
<input name="sex" value="Diesel" type="radio">Diesel<br>
<br>
<input value="add to cart"
onclick="parent.hello('Blue car')" type="submit"></form>
<br>
</body>
</html>
If you please can help me I would be so clad!
This is what happens when user clicks add to cart:
The onclick of the input fires, and the value of #anchorText is
changed to 'Blue car', which is passed to hello().
onsubmit fires from the form, and the value of #anchorText is
changed to undefined, since string is not passed.
To fix this, just remove the onsubmit attribute from the form, and pass the radio buttons instead of a string, for example:
Add this if to the hello():
function hello(string){
if (typeof string === 'object') { // Checks if an object is passed instead of a string
for (var n = 0; n < string.length; n++) { // Iterate through object
if (string[n].checked) { // Check, if the current radio button is checked
string = string[n].value; // Change the value of string to value of checked radio button
break;
}
}
}
var anchorText = document.getElementById('myAnchor').value;
:
}
and pass the radio buttons like this:
<input value="add to cart" onclick="parent.hello(document.getElementsByName('sex'));" ... />
Notice, that you still can use hello() to handle also strings, when a string is passed as an argument.
A live demo at jsFiddle. This fiddle is just an example to show how the code works in a single document.