I have a PHP form with different types of input fields (textbox, radio, checkbox,..) for which I used jQuery. It works fine for all input types except one of the question in my form for which the selected items(movies) by user are stored in an array. I think the image can explain better than me:
As can be seen in the image, selected movies by user are moved to the selected list(an array), while in jQuery validation, input names are "required" and therefore in this case only the value inserted in the textbox (in this case:"frozen") will be stored in database.
This is the code:
<form id="form2" action="page3.php" method="post">
<fieldset id = "q27"> <legend class="Q27"></legend>
<label class="question"> What are your favourite movies?<span>*</span></label>
<div class="fieldset content">
<p>
<div class="movienames">
<div class="field">
<Input type = 'radio' id="selectType" Name ='source' value= 'byTitle'>By title
<Input type = 'radio' id="selectType" Name ='source' value= 'byActor'>By actor
<Input type = 'radio' id="selectType" Name ='source' value= 'byDirector'>By director
</div>
<div id="m_scents" class="field">
<label style="margin-bottom:10px;" for="m_scnts"></label>
<p>
<input class="autofill4" type="textbox" name= "q27[]" id="q" placeholder="Enter movie, actor or director name here" />
<input type="button" value="search" id="btnSearch" />
</p>
<div>
</div>
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
</p>
</div>
</fieldset>
<script type="text/javascript">
var master_basket = new Array();
selectedMovies = {};
var selected;
var selectedVal;
var selectedDir;
$(document).ready(function () {
$("input[id='selectType']").change(function(){
$("#q").val('');
if ($(this).val() == "byTitle") {
//SOME LINES OF CODE....
.....
} else
if ($(this).val() == "byActor"){
// SOME LINES OF CODE
} else
if ($(this).val() == "byDirector"){
//SOME LINES OF CODE
}
});
$('#btnSearch').on('click', function (e) {
window.textbox = $('#q').val();
window.searchType = $('input:radio[name=source]:checked').val();
popupCenter("movielist.php","_blank","400","400");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k,v) {
var name_and_year = v.movie_name;
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
}
</script>
// CODE RELATED TO OTHER QUESTIONS IN THE FORM....
//.........
<input class="mainForm" type="submit" name="continue" value="Save and Continue" />
</form>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$('#form2').validate({
rules: {
"q27[]": {
required: true,
},
//OTHER REQUIRED QUESTIONS....
},
errorPlacement: function(error, element) {
if (element.attr("type") == "radio" || element.attr("type") == "checkbox" || element.attr("name") == "q12[]") {
error.insertAfter($(element).parents('div').prev($('question')));
} else {
error.insertAfter(element);
}
}
});
});
</script>
QUESTION:
I have two problems with my code:
When I click on "Save and continue" button to submit this page of
the form, for the mentioned question (the one you could see in the
image), only the value inserted in the textbox will be stored in
database while I need all selected movies in the list will be stored
in separate rows in DB.
The textbox for this question is a hidden field that will be
appeared only if user select one of the radio button values. So, if
user just ignore this question and doesn't select one of radio
button values, then he can simply submit this page and continue
without any error message.
I would like to know if there is a way to customize jQuery validation so that I don't let users to submit this page until they didn't answer the mentioned question?? and then, how could I store the selected items by user in Database instead of textbox value?
All ideas would be highly appreciated,
To submit the basket movie items you can add a hidden input field. You would get something like this:
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
$("#basket_content").append("<div type='hidden' name='basket_movie[]' value='"+v.movie_name+"' />");
Using this, there will be an array like $_POST['basket_movie'] which contains the movie names of the movies in the basket.
If you want to prevent submitting, when the input box isn't filled you just add an action listener on form submit and count the item_list items. If it's 0 then don't submit. Add something like this to prevent form submitting when there are no items added to the basket:
$(document).on('submit', '#form2',function(e)
{
if($('.item_list').length == 0)
{
e.preventDefault();
}
});
Related
I have a form where one of the controls(inside a div) has a display of none. When a user checks a particular radio button the hidden div will display which contains an input element allowing him to enter some input.
When I tested it with PHP (using isset() function), I realized that the input variable is set, even if it's parent(div with id of details) is not shown.
What I want however is that serialize should only send the variable to the server when the div containing the input field is displayed. If I however gives display of none to the input element directly, it works as I want. But I want it to be on the div because some controls like labels and many other possible input fields need to also be hidden. One quick solution will be to give all the controls or elements in the div a class and toggles their display using the radio buttons, but I rather prefer the class to be on the div wrapping them all.
HTML:
<form id="form">
<div class="form-group">
<label for="firstname">First Name</label>
<input type="firstname" class="form-control" name="firstname" autofocus placeholder="First Name">
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="surname" class="form-control" name="surname" placeholder="Surname">
</div>
<label>1. Do you program?: </label>
<label class="radio-inline">
<input type="radio" name="one" value="Yes"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="one" value="No" checked> No
</label>
<div class="form-group" id="details" style="display:none;">
<label class="control-label">State your Languages</label>
<input type="text" name="language" class="form-control" autofocus>
</div>
<div class="form-group">
<button id="submit" class="btn btn-primary">Submit</button>
</div>
</form>
JavaScript
$(function(){
$('#form input[name=one]').change(function(event) {
$('#details').toggle();
});
$('#submit').on('click', function(event) {
event.preventDefault();
var form = $('#form');
$.ajax({
url: 'process.php',
type: 'POST',
dataType: 'html',
data: form.serialize()
})
.done(function(html) {
console.log(html);
})
.fail(function() {
console.log("error");
})
});
});
PHP
if(isset($_POST['language'])) {
echo 'Language is set';
} else {
echo 'Not set';
}
The PHP reports 'Language is set' even if the div containing the input with name of language is given display of none;
disabled input elements are ignored by $.serialize()
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
To Temporarily enable them.
var myform = $('#myform');
// Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');
// serialize the form
var serialized = myform.serialize();
// re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');
OR
You could insert input fields with no "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jquery):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
Instead going for complex workaround in JavaScript, you could accomplish it in PHP easy way. Check if the radio button Yes is selected and if it is selected, you can do other processing based on that.
if(isset($_POST['one']) && $_POST['one'] === 'Yes') {
if(!empty($_POST['language'])) {
echo $_POST['language'];
} else {
echo "Language is given empty!";
}
} else {
echo 'Language is not selected!';
}
The PHP code above is a simple workaround. You could go for that. If you're only looking to do that in JavaScript itself, I would direct you to the answer given by Bilal. He has some workaround with JavaScript.
EDIT
I've come up with my own simple workaround in JavaScript. Hope it could help you.
<script>
$(function() {
var details = $('#details');
$('#details').remove();
$('#form input[name=one]').click(function() {
if(this.value === 'Yes') {
details.insertBefore($('#form div.form-group:last-of-type'));
details.show();
} else {
$('#details').remove();
}
});
});
</script>
Storing the reference to div of id details in a variable before removing the details div from the DOM.
Based on the value selected in the radio button, the details div will be added to the DOM and displayed or removed from the DOM in case No is selected.
Hope it helps!
I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
If you don't want to post the form you can use the preventDefault(); function.
$("button.form-control").click(function(event) {
event.preventDefault();
$("button.form-control-generate").show();
});
$("button.form-control").click(function(event) {
event.preventDefault();
setTimeout(function(){$("button.form-control-generate").show();},100);
});
Try It Once
Submit your form as
$('.form').on('submit', function(e){
$("button.form-control-generate").show();
e.preventDefault();
this.submit();
})
instead of using the click event. With button of type submit the submit() action is triggered automatically so you can show your button in the submit handler and then prevent the default action to refresh the page.
UPDATE:
Instead of using php you can do the same with jquery as well.
$('.form').on('submit', function(e){
e.preventDefault();
var date = new Date();
date = date.getYear() + 1900;
var data = $(this).serializeArray();
var str = data[0].value + date + data[1].value;
$('#output').text(str);
$('.form-control-generate').show();
})
.form-control-generate {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output"></div>
#ShubhamKhatri almost had it right
The problem is, he thought this was an on submit event, I don't believe it should be. I believe you have the type="submit" on the wrong button. Surely preview wouldn't submit the form? You want to submit on generate, no?
so a slight change to the markup - added an id to preview to make life simple
<button class="form-control" id="preview">
Preview
</button>
<br/>
<button class="form-control-generate" type="submit" name="submit">
Generate
</button>
and a slight modification to the code in #ShubhamKhatri answer
$("#preview").click(function(e) {
e.preventDefault();
var date = new Date();
date = date.getYear() + 1900;
var data = $('.form').serializeArray();
var str = data[0].value + ' ' + date + ' ' + data[1].value;
$('#footer_date').text(str);
$('.form-control-generate').show();
});
et voilà
now i have a input text, radio, and a submit button ..
lets say my url = image-search.php
<form>
<input type="text" name="name"><br>
<input type="radio name="arrange" value="horizontal"><br />
<input type="radio name="arrange" value="vertical"><br>
<input type="submit" name="submit"><br>
when i click the button..
it redirect same page but url = image-search.php?name=ss&arrange=horizontal
and this page still have the button..
the question is .. after i click button at 1st page = image-search.php
i want the user input value remain in the input text of name..
and how to make the checkbox as checked based on user choose?
If the page is reloaded when you submit the form you could use php to set default values for your form fields
<form>
<input type="text" name="name" value="<?php echo isset($_GET["name"])?$_GET["name"]:""; ?>"><br>
<input type="radio" name="arrange" value="horizontal"<?php echo (isset($_GET["arrange"])?($_GET["arrange"]=="horizontal"?" checked='checked'":""):""); ?>><br />
<input type="radio" name="arrange" value="vertical"<?php echo (isset($_GET["arrange"])?($_GET["arrange"]=="vertical"?" checked='checked'":""):""); ?>><br>
<input type="submit" name="submit"><br>
</form>
Here is the answer to your question.. hope this will help everyone..
#Macke - your approach for setting values after submission is really good, but when we have lot of elements on form.. let's say 1000 - it become pain in AS*..
Add this script tag in your HEAD tag of the page -
<script language="javascript" type="text/javascript">
var obj = JSON.parse('<?= json_encode($_REQUEST) ?>');
console.log(obj);
function __setPostBackValue(element){
if(obj.length <= 0) return;
var type = element.type;
var fval;
console.log('Processing...'+ element.name);
try{
eval('fval = obj'+'.'+element.name);
}
catch(ex){
}
if(type == 'text'){
element.value = fval;
}
if(type == 'checkbox'){
if(fval != undefined)
element.setAttribute("checked","on");
}
if(type == 'radio'){
if(fval != undefined && element.value == fval)
element.setAttribute("checked","on");
}
}
</script>
and at the bottom of the page, yes at the bottom of the page (before body ends) add another script tag -
<script language="javascript" type="text/javascript">
var fields = document.getElementsByTagName('input');
for(var i=0;i<fields.length;i++){
__setPostBackValue(fields[i]);
}
</script>
What it does ?
When you submit your form, var obj = JSON.parse('<?= json_encode($_REQUEST) ?>'); this creates local JSON Object usable by Javascript - and the script we added at the end of the page.. loop through all elements and call __setPostBackValue function. Where we are setting the values of the elements by Javascript.
This is little bit tricky but it works..!!
PS: I had no radio button in my page, but if you have you can add it easily.
-Paresh Rathod
Here is how the form is supposed to execute:
<script>
$(document).ready(function(){
$("#submit").click(function(){
//access token stuff
var token = $("#link_input").val(); ... etc</script>
.
I am trying to auto submit this info once it exceeds 10 characters. Normally you fill out the text area in the input field and you click submit. Upon clicking the submit button the JS validates the text in the input box and if it's valid it executes. How can I auto-submit the text in the input box without having to click the submit button?
<script language="JavaScript" type="text/JavaScript">
var x=10;//nr characters
function submitT(t,f){
if(t.value.length==x){
f.submit()
}
}
</script>
<input id="link_input" onkeyup="submitT(this,this.form)" autofocus="true" autocomplete="off" placeholder="http://www.facebook.com/connect/login_success.html#access_token=AAAZDCiOS6Ls0BAMUKJDvLZCTgZDZD" style="width: 600px;margin-left: -11%;" value="" name="url">
<br/>
<div id="Wait" style="display:none;"><center>Processing your form<br><img src="http://i.imgur.com/kKqSe.gif"></center></div>
<br/>
<center>
<img src="http://i.imgur.com/eA6fv.png" style="border:0px;padding-top:5px;">
$('#link_input').on('keyup', function() {
if($(this).val().length > 10) {
$('form').submit();
}
});
Just test against keyup similar to what you have already.
<form action='someplace' id='myform' method='post'>
<input type='text' id='link_input' ...other stuff />
</form>
jquery:
$('#link_input').on('keyup',function(){
var val = $(this).val();
var len = val.length;
if(len == 10){
$('#myform').submit();
}
});
Rename your btn from submit to btnSubmit.
The id of submit is going to mess with f.submit()
This shows result on selected radio button. I have a problem, when the page is refreshed no div shows and no result displays. I want show the Carsbuy div on page refresh.
$(document).ready(function() {
$("input[name$='mode']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#Cars" + test).show();
});
});
<input type="radio" name="mode" checked="checked" value="buy" />
<label>Buy</label>
<input type="radio" name="mode" value="rent" />
<Label>Rent</label>
<div id="Carsbuy" class="desc" style="display: none;">
Buy Cars Result Display Here On Select Buy
</div>
<div id="Carsrent" class="desc" style="display: none;">
Rent Cars Result Display Here On Select Rent
</div>
You can use following at the beginning of your js code to shoe specific DIV on page load:
$("#Carsbuy").show();
Edit:
for a specific DIV and radio button, use following:
var selected = 'rent';
$("div.desc").hide();
$("#Cars" + selected).show();
$('input[value="' + selected + '"]').attr('checked', true);
You can change the value of var selected to select a specific radio button and DIV
Demo
In the following code ,on page load check if a radio button is selected then its appropriate div is displayed . If condition is used to prevent if no radio button is selected
$(document).ready(function() {
var selected = $("input[type='radio']:checked").val();
if(selected !== 'undefined')
{
$("#Cars" + selected ).show();
}
$("input[type='checkbox']:checked").attr('id')
$("input[name$='mode']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#Cars" + test).show();
});
});
As much i understand your requirement, you can do it as below.
HTML:
<input type="radio" name="mode" checked="checked" value="buy" />
<label>Buy</label>
<input type="radio" name="mode" value="rent" />
<Label>Rent</label>
<div id="CarsDetails" class="desc">
// include buy type cars initialy while page load.
</div>
JQuery:
$(document).ready(function() {
$('input[type="radio"]').click(function() { // detect when radio button is clicked
var carType = $(this).val(); // get the value of selected radio type
$.ajax({
url : "cartype.php", // link to file containing data of cars
type : "GET", // request type
data : "carType="+carType, // send the selected car type (buy or rent)
datatype : "html",
success : function(response){ // get the response
$('#CarsDetails').html(response); // put the response in div.
}
});
});
});