Storing value in var from form submission with jQuery - javascript

I have looked at many answers and none seem to fit the issue. I have a simple search box and submit button, and want to store the value of the input field in a variable. It seems to store at first, then disappears. Code:
JavaScript
$(document).ready(function(){
$('form').submit(function(){
var input = $('#search').val();
$('p').append(input);
});
});
HTML
<form>
<input id='search' class='form-control' type='text' name='search'>
<input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
</form>
<p></p>
The variable will display for a second and disappear, presumably when the search box becomes empty again.

The reason this happens is because when you submit a form the browser will send a new HTTP request to the server and reload your page. You could prevent this behavior by returning false from the submit handler:
$('form').submit(function() {
var input = $('#search').val();
$('p').append(input);
return false;
});
or alternatively:
$('form').submit(function(e) {
e.preventDefault();
var input = $('#search').val();
$('p').append(input);
});
This will prevent the page from reloading and the changes you did to the DOM will remain.

$(document).ready(function(){
$('form').submit(function(){
var input = $('#search').val();
$('p').append(input);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id='search' class='form-control' type='text' name='search'>
<input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
</form>
<p></p>

For getting result you can do something like this
In HTML code
<form action="" method="get" id="search_form">
<input id='search' class='form-control' type='text' name='search'>
<input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
</form>
<p></p>
<div id="search_result"></div>
in Javascript code
$('#search_form').submit(function(){
var input = $('#search').val();
$('p').text(input);
$("#search_result").load($(this).attr("action")+ " #search_result", function(){
alert("result loaded for "+ input)
})
return false;
});

Related

I have to click the button twice to make the onclick work

Here is my html and JS code. When I first click on the button it submits the form but doesn't call the onclick function. I've tried adding onsubmit method to the form and make button type=button. However, that didn't change anything.
The form submission is for Django btw.
<form action='' method='GET' required id='form_id'>
<input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
<button class='submit-btn' type='submit' onclick="delayRedirect()">Listen</button>
</form>
JavaScript
function delayRedirect(){
setTimeout(function(){
window.location = 'player';
}, 1500);
}
Thanks in advance!
Changed the button type to button, and it logs "clicked." before submitting the form.
$('.submit-btn').click((e) => {
console.log('clicked.');
$('form').submit();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action='' method='GET' required id='form_id'>
<input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
<button class='submit-btn' type='button'>Listen</button>
</form>
<form required id='form_id'>
<input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
<button class='submit-btn'>Listen</button>
</form>
/JS
const btn = document.querySelector('.sumbit-btn')
btn.addEventListener("click", (e)=>{
e.preventDefault() // becuse the btn in <form></form>
// send to Django
})
HTML
<form action='' target="you_dont_see_me" method='POST' required id='form_id'>
<input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
<button class='submit-btn' type='button' onclick="delayRedirect()">Listen</button>
</form>
<iframe name="you_dont_see_me" style="display:none"></iframe>
JS
function delayRedirect(){
document.getElementById('form_id').submit();
setTimeout(function(){
//do whatever you want
}, 1500);
}
You can use iframe, but your method needs to be changed to POST.
I personally would use ajax to handle this kind of situation

JavaScript function which can validate multiple forms on a webpage

Apologies if this is a straightforward question, as I am still very new to JavaScript. I have a script that validates user inputs by checking if the text-field is empty. If it is not empty, then a confirmation window prompts the user to make sure they want to continue before the form is submitted and the information uploaded.
I would like to know how I can use the code below or similar code to validate multiple forms on the same page, as currently I can only get it to work with one single form? I have tried various solutions, non of which have yet been successful. I have even tried copy/pasting the entire script and changing the relevant elements inside it.
I've stripped my alterations to the code back to where it actually works correctly. Like I said, once I try to re-use it to validate multiple forms, the code stops working correctly.
// Set up event handlers in JavaScript
document.querySelector('form').addEventListener('submit', validationCheck);
document.getElementById('updateEventTitle').addEventListener('keyup', validationCheck);
// Get your DOM references just once, not every time the function runs
let eventTitle = document.getElementById('updateEventTitle');
let btnUpdate = document.getElementById('updateBtn');
function validationCheck(event) {
if (eventTitle.value === '') {
btnUpdate.disabled = true;
} else {
btnUpdate.disabled = false;
//Confirmation window
if (event.type === 'submit') {
//Confirmation window
var r = confirm('Do you want to update this item?');
if (r == true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
<input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>
I would like a script that is able to validate any HTML form on the page, not just the first one.
Many thanks.
We simply can took all the forms, loop through, get inputs and buttons we need for every form and set up listeners for every form, for every element.
Below is a code snippet explaining how it can be done.
// getting all forms
const elForms = [...document.querySelectorAll('form')];
// looping an array
elForms.map(elForm => {
// Get your DOM references just once, not every time the function runs
const elInput = elForm.querySelector(`input[type='text']`);
const elButton = elForm.querySelector(`input[type='submit']`);
// Set up event handlers in JavaScript
elForm.addEventListener('submit', (event) => validationCheck(event, elInput, elButton)); // passing parameters
elInput.addEventListener('keyup', (event) => validationCheck(event, elInput, elButton)); // passing parameters
});
function validationCheck(event, elInput, elButton) {
if(elInput.value==='') {
elButton.disabled = true;
} else {
elButton.disabled = false;
//Confirmation window
if(event.type === 'submit'){
//Confirmation window
var r =confirm('Do you want to update this item?');
if (r==true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
<input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>
After answer
There are duplicating id in your example
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle'
This is not valid and can cause problems in future. id should be unique.

jQuery/javascript to find/get values of form elements inside fieldset using ID

How can we get values of form elements inside fieldset?
<fieldset id='myFieldset'>
<label for='Resp'>Responsibilities</label><input id='input' type='text' size='55'>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='addItem'>Add</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='clear'>Clear</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='edit'>Edit</button>
<ul id='output' style='display:none'></ul>
<br class='clear' />
<textarea disabled name='Resp' id='Resp' cols='75' rows='5' required></textarea>
</fieldset>
I have some more fields similar to this in a page. So I need to get values from input form and also from specific fieldset. How can I do it in jQuery?
If you are using id attributes:
<input type="text" id="txtData" name="txtData" />
JQuery:
$("#myFieldset #txtData").val();
If you are using class attributes.
<input type="text" class="txtEmail" />
Jquery
$("#myFieldset .txtEmail").val();
You are able to get all ids value from fieldset as below:
Html
<fieldset id='myFieldset'>
<input type="text" id="txtData" name="txtData" />
<input type="text" class="txtEmail" />
<input type="button" class="btntest" />
</fieldset>
jQuery
$(".btntest").click(function () {
$("#myFieldset input[type != button]").each(function(key,value){
alert($(this).val());
});
});
So this thing will give you all inputs not then type = button value.
Here you go with the solution https://jsfiddle.net/f3xwzap9/
var data = {};
$('#addItem').click(function(){
$('fieldset#myFieldset > input, textarea').each(function(){
data[$(this).attr('id')] = $(this).val();
});
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id='myFieldset'>
<label for='Resp'>Responsibilities</label><input id='input' type='text' size='55'>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='addItem'>Add</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='clear'>Clear</button>
<button type='button' class='btn-sm' style='width:50px;margin:2px' id='edit'>Edit</button>
<ul id='output' style='display:none'></ul>
<br class='clear' />
<textarea name='Resp' id='Resp' cols='75' rows='5' required></textarea>
</fieldset>
I have attached an event in Add button.
I'm looping through all the input & textarea inside the fieldset & collecting the data.
Data is in JSON format id as key and value is value.
Since I'm looping through all the input & textarea, it will help you to collect all the child (input & textarea) data, rather than collecting the data specifically.
Try this:
var inputVal = $('#myFieldset #input').val();
var textAreaVal = $('#myFieldset #Resp').val();
$('#myFieldset').find('input').val()

How to solve validation using multiple buttons in a form

I have a form, with a number of textboxes which a user can fill in. At the bottom of the form I have two buttons. One for canceling and one for submitting. Like the example below
<form action='bla.php' method='post'>
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<input type='submit' name='submit'>
<input type='submit' name='cancel'>
</form>
And I have a js function that checks the fields for their data which I used to use for both buttons. I therefor refer to the js function in the form as below:
<form action='bla.php' method='post' name='form' onSubmit='return CheckFields()'>
The js function looks like this:
function CheckFields() {
var formname = "form";
var x = document.forms[formname]["someTextField1"].value;
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
Now I want this js function to only run when using the submit and not the cancel button. When I try to move the call to the function to the submit button as below it doesn't work:
<input type='submit' name='submit' onClick='return CheckFields()'>
<input type='submit' name='cancel'>
Why? What is the smartest way of solving this? Should I leave the call to CheckFields() in the form and check within the script what button was clicked or should I remake the function to somewhat work with a button instead? Anyone have an idea or an example?
replace <input type='submit' name='cancel'> by <input type='button' name='cancel'>.Your Version actually has two submit-buttons, both of which will submit the form.
Watch this sample http://jsfiddle.net/355vw560/
<form action='bla.php' method='post' name="form">
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<br/>
<input type='submit' name='submit' onclick="return window.CheckFields()">
<input type='submit' name='cancel' value="cancel" onclick="return false;">
anyway it's always better to use jquery or event listeners instead of managing events directly in the dom.
The function didnt worked because its scope was the element, if u specify window as context your function works.
First at all, it's not needed have submit button on a form if you want to use javascript to check all the fields before submitting.
I think the smartest way of doing it will be as follow:
Your form (without action, submit button, and method. Only identifing each component with id's):
<form id="formId">
<input type='text' id="text1">
<input type='text' id="text2">
<input type='text' id="text3">
<input type='button' id="accept">
<input type='button' id="cancel">
</form>
Your javascript (you have to have jQuery added):
jQuery("#formId").on("click", "#accept", function(){ //listen the accept button click
if(CheckFields()){ //here you check the fields and if they are correct
//then get all the input values and do the ajax call sending the data
var text1 = jQuery("#text1").val();
var text2 = jQuery("#text2").val();
var text3 = jQuery("#text3").val();
jQuery.ajax({
url: "bla.php",
method: "POST",
data: {
"someTextField1":text1, //In your example "someTextField1" is the name that the bla.php file is waiting for, so if you use the same here, it's not needed to change anything in your backend.
"someTextField2":text2,
"someTextField3":text3
},
success: function(){
//here you can do whatever you want when the call is success. For example, redirect to other page, clean the form, show an alert, etc.
}
});
}
});
jQuery("#formId").on("click", "#cancel", function(){ //here listen the click on the cancel button
//here you can clean the form, etc
});
function CheckFields() { //here I did a little change for validating, using jQuery.
var x = jQuery("#text1").val();
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
I hope it helps you!
I handle it with this way , Hope it will help.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form method="post" action="/">
<div class="container" style="background: #efefef; padding: 20px;">
<label>Encrypt and decrypt text with AES algorithm</label>
<textarea name="inputText" id = "inputText" rows="3" cols="100" placeholder="Type text to Encrypt..." maxlength="16" ></textarea>
<br>
<br>
<textarea name="inputKey" id = "inputKey" rows="1" cols="100" placeholder="Type key to Encrypt\Decrypt text with..." maxlength="16"></textarea>
<br>
<br>
<label>SBox :</label>
<div>
<div class="s-box-radios">
<ul class="sbox">
<li>
<label>SBox 1
<input id="sbox1" name="sboxOption" type="radio" value="option1" required/>
</label>
</li>
<li>
<label>SBox 2
<input id="sbox2" name="sboxOption" type="radio" value="option2" />
</label>
</li>
<li>
<label>SBox 3
<input id="sbox3" name="sboxOption" type="radio" value="option3" />
</label>
</li>
<li>
<label>SBox 4
<input id="sbox4" name="sboxOption" type="radio" value="option4" />
</label>
</li>
</ul>
</div>
<div class="s-box-display">
<textarea rows="5" cols="10"></textarea>
</div>
</div>
<div class="clear"></div>
<br>
<label>Result of Decryption in plain text</label>
<textarea name="inputCipher" rows="3" cols="100" placeholder="Encrypted Texts..." name="decrpyted"></textarea>
<br>
<input type="submit" value="Encrypt" name="Encrypt" id ="encrypt" onclick="valEncrypt()" />
<input type="submit" value="Decrypt" name="Decrypt" id ="decrypt" onclick="valDncrypt()" />
</div>
</form>
<script>
function valEncrypt()
{
var inputText = document.getElementById('inputText');
var inputkey = document.getElementById('inputKey');
if (inputText.value.length <16)
{
doAlert(inputText);
return false;
}
else
{
removeAlert(inputText);
}
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
else
{
removeAlert(inputkey);
}
}
function valDncrypt()
{
var inputkey = document.getElementById('inputKey');
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
alert('!Success');
}
function doAlert(element){
element.style.border = "1px solid #FF0000";
}
function removeAlert(element){
element.style.border = "1px solid #000000";
}
</script>
</body>
</html>

Use a form field input to set an anythingSlider value

I can't seem to figure out how to make a form input box such that when you click a submit button, the value of that input box is updating this slider
http://css-tricks.com/anythingslider-jquery-plugin/
$('#myForm').click ( function() { $('#slider').anythingSlider(formVal); } )
After reading your comment and fixing your question, I think you mean
<script>
$(document).ready(function() {
$('#myButton').click(function() {
$('#slider').anythingSlider($("#myField").val());
})
});
</script>
<form>
<input type="text" id="myField" value="" />
<input type="button" id="myButton"/>
</form>
Create an input box and a button in html body
<form>
<input id='input1' name='input1' />
<input type='button' value='Submit' id='submit' onclick='onSubmit()' />
</form>
Add this function to your javascript
function onSubmit() {
formVal = document.getElementbyId('input1').value
}
For your case, use JQuery as
$document.ready(function() {
$('#submit').click(function() {
var formval = $('$inpupt1').val();
$('#slider').anythingSlider(formVal);
});
});

Categories