Jquery, adding input element - php

i have successfully added input element into div, which looks like this :
$(document).ready(function() {
$('#jumlah').change(function() {
var jum = $('#jumlah').val();
for(i=1;i<=jum; i++){
$('#jawaban').append('<label>Jawaban Soal ' + i + ' : </label><input type="text" name="jawab'+i+'" id="jawab[]" size="2" maxlength="1" /><br>');
}
});
});
and some my HTML codes are :
<select name="jumlah" id="jumlah" class="test">
<option value="0" selected="selected">choose value</option>
<?php
for($i=1;$i<=20;$i++)
echo("<option value=\"$i\">$i</option>");
?>
</select>
<div id="jawaban"></div>
but when i choose different value, it appends more input elements under the first ones, for example, if i choose option 2 and then option 3 it will look like :
Jawaban Soal 1 : <input />
Jawaban Soal 2 : <input />
Jawaban Soal 1 : <input />
Jawaban Soal 2 : <input />
Jawaban Soal 3 : <input />
Please help, i'm still junior in Jquery. I'm looking forward to your respond.

I'm guessing you want the old ones to disappear, in which case you should empty the jawaban div first.
$(document).ready(function() {
$('#jumlah').change(function() {
var jum = $('#jumlah').val();
$('#jawaban').empty();
for(i=1;i<=jum; i++){
$('#jawaban').append('<label>Jawaban Soal ' + i + ' : </label><input type="text" name="jawab'+i+'" id="jawab[]" size="2" maxlength="1" /><br>');
}
});
});
You (infact a considerable amount of people), should cache the jQuery objects you build. Each time you use $('someSelector') in your code, jQuery re-selects your elements, and returns a new object for you each time. this is none trivial!
$(document).ready(function() {
$('#jumlah').change(function() {
var jum = +$('#jumlah').val(); // convert this to an integer (it's a string otherwise)
var jawaban = $('#jawaban').empty();
for(var i=1;i<=jum; i++){ // don't forget to initialize i!
jawaban.append('<label>Jawaban Soal ' + i + ' : </label><input type="text" name="jawab'+i+'" id="jawab[]" size="2" maxlength="1" /><br />');
}
});
});

Related

posting array of text fields using jquery and ajax

i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.

Pass data from dynamic select box with ajax to php without submit or reload

I want to create two select boxes: One that gets it's options from a database and the other that gets it's options depending on the value of the first select box.
My current code is below (I got the value from the first box with an alert, but don't know how to get it in the sql query for the second box). My document name is tutorial.php and I'm not using any other files except for the database functions, which are in include/config.php.
I've followed dozens of tutorials and stack overflow answers, but I can't get it to work. How can I get the select values to the php code on the same page?
jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="js/script.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( "#shoot" ).change(function(){
id_firstSelect = $("#shoot").val();
loadSecondSelect(id_firstSelect);
});
function loadSecondSelect(first_id)
{
$("#model").ready(function(e)
{
$.get(
route.php, //Filter your select
params, // In this case your id
function(result)
{
$("#model").empty();
$("#model").append('<option value="0">-- Select --</option>');
if(result.response['id_second'].length) // this receive your data
{
for(var i=0, len=result.response['id_2'].length; i<len; i++)
{
$("#model").append('<option value="' + result.response['id_2'][i] + '">' + result.response['name_2'][i]+'</option>');
}
}
},
"json");
});
}
});
</script>
form with php functions:
<form action="" method="POST" enctype="multipart/form-data">
<div>
<select name="category">
<option value="paard" selected>Paarden</option>
<option value="hond">Honden</option>
<option value="mens">Mensen</option>
<option value="eigen">Eigen werk</option>
</select>
<input type="file" name="files[]" multiple id="file"/><p>
Ophalen uit database shoots:
<select name="shoot" id="shoot">
<?php
$values = mysql_query("SELECT distinct name FROM shoots") or die(mysql_error());
//$numrows = mysql_num_rows($values);
while ($result=mysql_fetch_array($values)){
echo "<option value='".$result['name']."'>".$result['name']."</option>";
}
?>
</select><p>
<select name="model" id="model"></select>
<label class="radio">Portfoliomateriaal</label>
<input type="radio" name="folio" value="TRUE" /> <span>Ja</span>
<input type="radio" name="folio" value="FALSE" checked /> <span>Nee</span><p>
<input type="submit" value="Upload" id="submit" />
</div>
</form>
In the first select, you could call a function with the id of the select to filtrate the data of the second select like:
in the first select you could do this to fill the second with the first id:
$( "#id_firstSelect" ).change(function()
{
id_firstSelect = $("#id_firstSelect").val();
loadSecondSelect(id_firstSelect);
}
and call the function to load the second select
function loadSecondSelect(first_id)
{
$("#id_secondSelect").ready(function(e)
{
$.get(
route.php, //Filter your select
params, // In this case your id
function(result)
{
$("#id_secondSelect").empty();
$("#id_secondSelect").append('<option value="0">-- Select --</option>');
if(result.response['id_second'].length) // this receive your data
{
for(var i=0, len=result.response['id_2'].length; i<len; i++)
{
$("#id_secondSelect").append('<option value="' + result.response['id_2'][i] + '">' + result.response['name_2'][i]+'</option>');
}
}
},
"json");
});
}

I am so confused by checkboxes in Ajax

I am attempting to create an ajax contact form that the results gets emailed to me. I found a form demo online and edited it to meet my criteria, except that there were no checkboxes in the demo, when I add checkboxes everything but those work.
Can someone please guide me through this?
The html is:
<div class="done">
<strong>Thank you !</strong> We've received your questions and someone from our office will respond at our earliest convience.</p>
<p>Check your email, we just sent you a coupon for 10% off your first purchase.</p>
</div>
<div class="form">
<form method="post" action="process2.php" autocomplete="off">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<ul>
<li>Design:</li>
<li><label for="master_plan"><input type="checkbox" name="service[]" id="master_plan" value="Master Plan" /> Master Plan</label></li>
<li><label for="front_foundation"><input type="checkbox" name="service[]" id="front_foundation" value="Front Foundation" /> Front Foundation</label></li>
<li><label for="backyard_plan"><input type="checkbox" name="service[]" id="backyard_plan" value="Backyard Plan" /> Backyard Plan</label></li>
<li><label for="specialty_garden"><input type="checkbox" name="service[]" id="specialty_garden" value="Specialty Garden" /> Specialty Garden</label></li>
</ul>
<label for="newsletter"><input type="checkbox" name="newsletter" id="newsletter" value="x" checked="checked" /> Yes, I would like to be added to your newsletter list.</label>
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="5" cols="40" /></textarea>
<input type="submit" id="submit" value="Sign Up" />
<div class="loading"></div>
</form>
</div>
The javascript is:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process2.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
And the php (process2.php) is:
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$mailing = ($_GET['newsletter']) ?$_GET['newsletter'] : $_POST['newsletter'];
$comments = ($_GET['comments']) ?$_GET['comments'] : $_POST['comments'];
if($phone) {$phone = '('.substr($phone, 0, 3).') '.substr($phone, 3, 3).'-'.substr($phone, 6, 4);} else {$phone = '(Not Entered)';}
I am so very confused that I dont know what to do?
You aren't including them in your data that you're sending via ajax. You're also not even trying to get the service values in your php.
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&comments=' + encodeURIComponent(comments.val());
//data only includes name, phone, email, comments
You might want to try jQuery serialize method instead of the above code.
var data = $(this).parents('form').serialize();

radio is only passing the first value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get which radio is selected via jQuery?
I am attempting to put a user rating system on my site but only the first value gets passed on, so in the table the rating column is always a one. Its been a while since I have worked with radios.
Here is what I have.
<form id="add-rateing">
<input type="radio" name="MOVIE_RATING" value="1" > 1
<input type="radio" name="MOVIE_RATING" value="2" > 2
<input type="radio" name="MOVIE_RATING" value="3" checked="yes"> 3
<input type="radio" name="MOVIE_RATING" value="4" > 4
<input type="radio" name="MOVIE_RATING" value="5" > 5 <br>
<input type="hidden" name="MOVIE_ID" value="<?php echo $id; ?>">
<input type="hidden" name="MOVIE_TITLE" value="<?php echo $title; ?>">
<input type="hidden" name="USER_ID" value="<?php echo $loggedinusername; ?>">
<input type="submit" value="I Drank To The Credits" onclick="$('#add-rateing').hide('fast')">
</form>
<script type="text/javascript">
$("#add-rateing").submit(function(event){
event.preventDefault()
addrateing();
});
function addrateing()
{
var movie_rating_s = $("#add-rateing [name='MOVIE_RATING']").val();
var movie_id_s = $("#add-rateing [name='MOVIE_ID']").val();
var movie_title_s = $("#add-rateing [name='MOVIE_TITLE']").val();
var user_id_s = $("#add-rateing [name='USER_ID']").val();
var errors = '';
$.ajax({
type : "POST",
url : "movie_watched.php",
data : { rating: movie_rating_s,
movie : movie_id_s,
title: movie_title_s,
user : user_id_s, },
cache : false, timeout: 10000,
success : function() {
alert("You have played <?php echo $title; ?> ");
},
error : function() {
alert("there is a problom");
},
complete : function() {
}
});
};
</script>
Try chaging this :
var movie_rating_s = $("#add-rateing [name='MOVIE_RATING']").val();
into this:
var movie_rating_s = $("#add-rateing [name='MOVIE_RATING']:checked").val();
You need to select the selected radio element, like so:
$('input[name="MOVIE_RATING"]:checked').val();
It looks like the problem is with your jQuery selector. It's not specifying to grab the value of the "checked" radio button. Try this when loading up your movie_rating_s variable:
var movie_rating_s = $("#add-rateing [name='MOVIE_RATING']:checked").val()

How to set selected value of dynamic drop down using jquery?

I have a drop down list which is dynamically generated using ajax on page load.
On the other hand I have a php variable which contains the value to be selected by default.
However, when Iam trying to do this it isn't selecting the value. Following is code:
HTML & PHP
<h1>Venue: Edit</h1>
<< Back to Venue List
<br />
<form method="post" id="venueEdit" action="<?php echo URL;?>venue/editSave/<?php echo $this->venue['id']; ?>">
<fieldset>
<p>
<label for="cvenue" class="main">Venue</label>
<input id="cvenue" class="required" type="text" name="venue" value="<?php echo $this->venue['name']; ?>" />
</p>
<p>
<label for="ccity" class="main">City</label>
<input id="ccity" class="required" type="text" name="city" value="<?php echo $this->venue['city']; ?>" />
</p>
<p>
<label for="ccountry" class="main">Country</label>
<select id="ccountry" class="required" name="country">
<option value="">-- Select Country --</option>
</select>
</p>
<p>
<label class="main"> </label><input type="submit" value="Save" />
</p>
</fieldset>
</form>
JS:
function populateCountryDropDown(url){
$.get(url, function(o) {
for(var i = 0; i < o.length; i++){
$('select[name="country"]').append('<option value="' + o[i].id + '">' + o[i].name + "</option>");
}
}, 'json');
}
$(document).ready(function(){
populateCountryDropDown('<?php echo URL; ?>' + 'country/xhrGetCountryList');
$('select[name="country"]').val('<?php echo $this->venue['countryid']; ?>');
$("#venueEdit").validate();
});
I tried to alert the php value and it's ok but if I alert the select option value it's always null as at that point it's still populating the drop down list. I don't know how to solve this. Would appreciate your guys help? Thanks.
You need to move your code to set the value into the callback, to trigger the value being set after the AJAX call fired off by $.get() returns.
function populateCountryDropDown(url){
$.get(url, function(o) {
for(var i = 0; i < o.length; i++){
$('select[name="country"]').append('<option value="' + o[i].id + '">' + o[i].name + "</option>");
}
$('select[name="country"]').val('<?php echo $this->venue['countryid']; ?>');
$("#venueEdit").validate();
}, 'json');
}
$(document).ready(function(){
populateCountryDropDown('<?php echo URL; ?>' + 'country/xhrGetCountryList');
});
This code here:
$('select[name="country"]').val('<?php echo $this->venue['countryid']; ?>');
Try changing to:
$('select[name="country"]').val('<?php echo $this->venue["countryid"]; ?>'); // Double quotes around countryid vs the single quote.

Categories