$('#submit').click(function(){
$.post(
'/foo.php',{
name:myform.name.value,
interest:myform.interest.value,
interest2:myform.interest2.value...
}
});
<input type="button" value="Add more interest" />
I have a form use jquery post. There is a button can append more input type text.
My questions
1 when user click and append more input field, in side of $.post(... how can I add more script, so I can post it to next page?
2 in my php page
if(isset($_POST['interest1'], $_POST['interest2']...)){}
how can I know how many extra input fields user has added?
3 how can I limit maximum 3 input fields user can append?
Are you setting form fields manually in your post request?
Bad idea, you'd be better of using jQuery's serialize method:
$.post("/foo.php", $("#myForm" ).serialize() );
For your second question: use array naming on your form elements:
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
This way you get an array in your post array and can use it like so:
foreach ($_POST['interest'] as $interest) {
doStuff();
}
For your third question I'm assuming you wrote a JS method that
adds an input field to the form? If so you could implement
a limit this way:
window.formFieldCount = 1;
function addFormField() {
if (window.formFieldCount >= 3) {
alert('You can only add three interests!');
return false;
}
// Do your form magic here
window.formFieldCount++;
}
HTML:
<form name="some_name">
<div id="interests">
<input type="text" name="interests[]" />
</div>
<input id="more-interests" type="button" value="Add more interest" />
<input id="submit" type="button" value="Submit" />
</form>
Javascript:
$(document).ready(function(){
var maximumNumberOfInterests = 3;
$('#more-interests').click(function(e){
if ($("input[name='interests[]']").size() < maximumNumberOfInterests) {
$('#interests').append('<input type="text" name="interests[]" />');
} else {
alert('The maximum number of interests has been reached!');
}
});
$('#submit').click(function(){
$.post('/foo.php', $('form').serialize());
});
});
PHP:
if (count($_POST['interests'])) {
foreach ($_POST['interests'] as $interest) {
echo $interest;
}
}
Here is a DEMO of the HTML/Javascript part
q2. can you change form like this:
static inputs
<input name='static[something]'>
<input name='static[somebody]'>
<input name='static[etc]'>
and dynamically generated inputs
<input name='dynamic[]'>
<input name='dynamic[]'>
<input name='dynamic[]'>
php
if (isset($_POST['dynamic']))
{
foreach ($_POST['dynamic'] as $key => $value)
{
/* do some shit with dynamic inputs */
}
}
Please use prepend function before form submit
Like
$("#myForm").prepend("<input type=\"text\" name=\"interest"+counter+"\"").submit(function(){
console.log($("#myForm" ).serializeArray())
$.post(Event.target.action, $(Event.target).serializeArray(), function(data){
// your code here
})
return false;
})
Related
I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})
I have recently set up https://github.com/loopj/jquery-tokeninput on one of my web sites.
I am trying to allow the users of the sites to create a list from a number of options that I give them.. Once the user is done selecting all their items and click submit I get no values back.
Can anyone let me know what I am doing wrong..
HTML
<div>
<input type="text" id="demo-input" name="name" />
<input type="Submit" value="Submit" />
</div>
JS
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input").tokenInput("json.php");
});
</script>
PHP
$name =$_POST["name"]);
This is what I am doing so far to get around the issue..
As the user adds and removes items from the list I am using the onAdd and onDelete functions to add the id's to a hidden field .. Once all the ID's are populated I can use the standard $_post[] command in php to read the values
here is a sample of the code for anyone else who might have the same issue
HTML
<div>
<input type="text" id="list_of_items" name="list_of_items" />
<input type="hidden" id="list_of_items_by_id" name="list_of_items_by_id" />
<input type="Submit" value="Submit" />
</div>
JS
$(document).ready(function(){
var field_value = $("#list_of_items_by_id").val();
$("#list_of_items").tokenInput("json.php",{
hintText: "Start typing the name of the item",
tokenValue:"item_id",
onAdd: function (item) {
var field_value = $('#list_of_items_by_id').val();
if (field_value != ""){
$('#list_of_items_by_id').val(field_value+","+ item.item_id);
}else{
$('#list_of_items_by_id').val(item.user_id);
}
},
onDelete: function (item) {
var field_value = $('#list_of_items_by_id').val().replace(',,',',').replace(item.user_id,'');
$('#list_of_items_by_id').val(field_value);
}
});
});
I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle
I am trying to see if a checkbox got checked with is() method, but it is giving an unexpected result. Either way if I check the checkbox or not, the method is returning false.
HTML
<form action="" method="post" id="place_order">
<input type="checkbox" name="tos" class="required check-condition" />
<span class="error error-tos" style="display:none">* This field is required</span><br>
<input type="submit" name="place_order" value="Submit Order" class="order-sb-btn" />
</form>
Jquery
$("#place_order").submit(function () {
var is_tos_checked = $(".check-condition").is('checked');
console.log(is_tos_checked);
if (is_tos_checked) {
$(".error-tos").hide();
return true;
} else {
$(".error-tos").show();
return false;
}
});
Jsfiddle
http://jsfiddle.net/yogc5ypb/1/
You need to express checked as a pseudo-selector, i.e. prefixed with :
.is(':checked');
I usually use .prop('checked')
So in your code you would change your line to:
var is_tos_checked = $(".check-condition").prop('checked');
If you want to submit form if user checked check box then you can use following method also-
1.write following statement in html file
<form action="" method="post" id="place_order">
<input type="checkbox" name="tos" class="required check-condition" />
<span class="error error-tos" style="display:none">* This field is required</span><br>
<input type="submit" name="place_order" value="Submit Order" class="order-sb-btn" />
</form>
2.Write following statement in js file.
jQuery('.order-sb-btn').click(function(){
var checkedValue = $('.required:checked').val();
if(checkedValue == undefined)
{
alert('not checked');
return false;
}
else
{
alert('checked');
}
})
By using above code form will be submit if user check the checkbox.
To check example please refer following link-
http://jsfiddle.net/1eygh774/1/
I just a got a requirement to disable the send button in the form until the users enter his data.Can any one guide me?
thanks
Have the button initially disabled by having such HTML
<input type="submit" id="btnSubmit" disabled="disabled" value="Send" />
Then in the blur event of your form elements check if user entered all required data and when this happens, enable the button using such code:
document.getElementById("btnSubmit").disabled = false;
form action="javascript:aNameForAnAjaxSendPostFunction"
function aNameForAnAjaxSendPostFunction()
{
if ((document.getElementById('your field').value.strlen>0))
{
<< SEND REQUEST >>
}
}
Normally, I would code it for you, but I'm in a hurry, and you do have to learn how to search for yourself, so here's a hint:
addEventListener(), and you can check the length of the data within an input by calling document.body.getElementById('yourInput').length, and then you can change the button.disabled property to either true (make the default value false in the source code). All you need to do for yourself is find out how to use addEventListener
A simple way of doing what you want using JQuery:
(this works if you have only input texts)
HTML:
<form method='POST' action=''>
<input type='text' name='name' />
<input type='text' name='phone' />
<input type='text' name='email' />
<button type='submit' disabled='disabled'>Send</button>
</form>
Javascript:
$(function() {
$("input").change(function() {
if($("input[value='']").length == 0) {
$("button").removeAttr("disabled");
} else {
//disable again if a field is cleared
$("button").attr("disabled",true);
alert("Please fill all fields");
$("input[value='']").eq(0).focus();
}
});
});