creating dynamic fields and fill the data in it - php

I have below JSON data and HTML form, in which dynamically fields get created. This form work to send the data. But how to fill the fields by dynamically creating them
json data
$data = {"1":"a","3":"b","5":"c","2":"d","4":"e"}
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-compat-git.js"></script>
<title>Add/Remove Input Fields Dynamically with jQuery</title>
<script type="text/javascript">
$(function() {
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
});
</script>
</head>
<body>
<form role="form" action="" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<select name="id[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="text" name="stuff[]">
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
<input type="submit">
</form>
</body>
</html>
Any help will be appreciated.

You need a loop. In javascript you do something like:
var $data = {"1":"a","3":"b","5":"c","2":"d","4":"e"};
var formHTML = "";
$.each($data, function(key, value) {
var inputHTML = "<input name='"+key+"' value='"+value+"' type="text"/>\n";
formHTML += inputHTML;
});
And then append formHTML inside your form.

Related

Dropdown list not work with data-native-menu="false"

I use dropdown list with PHP to retrieve data from my sql database, It exists on this link.
It worked well but when I change the menu style what I want, does not work.
this menu code is what I want:
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
I think the problem exists because the menu shows in popup : `#&ui-state=dialog`
but I do not know how to solve this problem.
this full HTML code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>
Please help

How can I submit a form without reloading the page

I have this html example form that I need to submit to MySQL table without having to refresh the page. Basically the main idea is to keep the username value in the input field after the data is sent. I have been struggling for days trying to use Ajax and JQuery functions to achieve my goal but I cannot get it right, that's why I'm only posting this piece of html code, I'm open to ideas, if you can please provide some code. Thank you so much.
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" name="form">
name:<input id="name" name="name" type="text" />
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="submit" value="Submit" class="submit"/>
</form>
</body>
</html>
Inside my php file:
<?php
$dbhost = 'localhost';
$dbuser = 'Myuser';
$dbpass = 'Mypass';
$db = 'Mydb';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db);
$name = $_POST['name'];
$gender = $_POST['gender'];
mysql_query("INSERT INTO callWrapper ('user','data')
VALUES ('$name','$gender'") or die(mysql_error());
?>
Use event.preventDefault() in jQuery:
$("form").submit(e) {
e.preventDefault();
// the rest of your code
}
See here for more details.
If you do not want to use jQuery, you can do it like this:
<form onsubmit="myFormFunction();return false">
Bear in mind these do slightly different things as explained here
HTML:
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" name="form" id="frm_data">
name:<input id="name" name="name" type="text" />
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="button" value="Submit" class="submit" id="btn_submitForm"/>
</form>
</body>
</html>
JS:
// bind click event
$('#btn_submitForm').click(function(e){
e.preventDefault();
var url = 'Your PHP File URL';
var formData = $("#frm_data").serializeObject();
$.post(url, formData,
function(data) {
//alert(data);
}
);
});
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#frm_data").submit(function(){
$.ajax({
type: "POST", // data send format POST/GET
url: "./process_form.php", // file url for data processing
data: $("#frm_data").serialize(), // all form field are serialize
dataType: "json", // response type xml, json, script, text, htm
success: function(data) {
alert('hi');
}
});
});
});
</script>
</head>
<body>
<form method="post" name="form" id="frm_data" onsubmit="return false;">
name:<input id="name" name="name" type="text" />
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="submit" value="Submit" class="submit" id="btn_submitForm"/>
</form>
</body>
</html>
for the reference check the url : http://api.jquery.com/jquery.post/

jQuery Dropdown Menu + PHP - keeping selection

I'm not very experienced at JS (PHP is my strong side) so I need your help about something.
I have a script with 2 drop down menus that shows hidden content. I'm using this example Change content based on select dropdown id in jquery
When I execute a PHP script, it checks for errors and if there are some it will return the user to the form. The problem with this is that it will not show the hidden content. I can set some sort of PHP vars and put them in the input like $selected_one = 'selected="selected"' and the dropdown menus will have the right selection, but the jQuery function does not work like that. I think it puts some sort of class that shows and hides the content.
I can't quite put my finger on what's going on, so I need your help. Can any body give me a hint how to fix this?
Here's some code to make things visual
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<style>
.list_publish, .list_news, option_value {
display: none;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<?php
$selected_news = '';
$selected_review = '';
$selected_news_text = '';
$selected_news_video = '';
if(isset($_POST['submit_news_text'])){
$selected_news = 'selected="selected"';
$selected_news_text = 'selected="selected"';
$news_title = $_POST['news_title'];
// Checks blank forms and return error
if(empty($news_title)) {
$error_message = 'This field must not be empty!';
$proceed = false;
} else {
$proceed = true;
}
}
if($proceed){
// do stuff
echo 'do stuff';
} else {
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<select class="change_publish" name="publish_type" id="publish_type" style="width: 238px;">
<option value="publish_type" data-title="choose">Publishing...</option>
<option value="publish_news" data-title="news" <?php echo $selected_news ?>>Publish News</option>
<option value="publish_review" data-title="review" <?php echo $selected_review ?>>Publish Review</option>
</select>
<div class="list_publish publish_type">
</div>
<div class="list_publish publish_news">
<select class="change_news" name="news_type" id="news_type" style="width: 238px;">
<option value="news_type" selected="selected" data-title="choose">News Type</option>
<option value="news_text" data-title="text" <?php echo $selected_news_text; ?>>Text</option>
<option value="news_video" data-title="video"<?php echo $selected_news_video; ?>>Video</option>
</select>
<div class="list_news news_type">
</div>
<div class="list_news news_text">
<input name="news_title" type="text" id="news_title">
<input name="submit_news_text" type="submit" value="Publish" id="submit_news_text" />
</div>
<div class="list_news news_video">
> This function is not available at the moment.
</div>
</div>
<div class="list_publish publish_review">
> This function is not available at the moment.
</div>
</form>
<?php
echo $error_message;
}
?>
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
</script>
</body>
</html>
And here's a demo http://www.demirevdesign.com/public/form.php
Trigger the change event on document load, like here:
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
</script>

How to pass the jquery hidden value to php

in my code i am creating a drop down box and storing the changed value of the drop down in hidden variable.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select id="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="hidden" id="inputfield">
<div></div>
<script type="text/javascript">
$(document).ready(function() {
$("#sweets").change(function() {
var var_name = $(this).val();
$('input[id=inputfield]').val(theValue);
}
});
});
});
</script>
</body>
</html>
<?php
if(isset($_POST['form']))
echo $_POST['inputfield'];
?>
once the combo box is changed the php should get the hidden field value and i ve to perform db transaction. again i need to load another drop down box based on the selected value.. Can you guide me
You can bypass all the horse trading with the hidden field and send it to php directly via ajax.
$(document).ready(function() {
$("#sweets").change(function() {
$.post('myphpfile.php', {sweet : $(this).val() });
});
});
myphpfile.php will receive the value as a post with the name of 'sweet'
Unless I'm misunderstanding, shouldn't
$('input[id=inputfield]').val(theValue);
be
$('input[id=inputfield]').val(var_name);
?
You can wrap the select and hidden elements in form element adding a post method and action attribute. Give the hidden field a name as in name="hidden field"
this way you can access it in the post variable.
<form action="currentpage.php" method="post">
<select id="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="hidden" id="inputfield" name="hiddenfield"/>
<input type="submit" value="Submit" name="submit"/>
</form>
When the change event executes to update the hidden field and you submit in php you can do
if(isset($_POST["submit"]))
{
$val = $_POST["hiddenfield"] ;
}

Use HTML variable inside JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)
Let's say there is some PHP file called as scheduler.php. It contains a script
<script>
window.setInterval(function(){
find_opt_schedule();
}, 60000);
</script>
... and some PHP code:
<form action="scheduler.php" method="post">
<select name="refresh" id="refresh">
<option value="30000">30000</option>
<option value="60000" selected>60000</option>
<option value="120000">120000</option>
</select>
</form>
How do I use the value selected by the user from refresh select list inside the script? In particular, I want to replace 60000 by the variable that must be selected by the user from the list. I tried this, but the refresh rate is very high instead of 60000 miliseconds.
window.setInterval(function(){
find_opt_schedule();
alert(<?php echo (int)$_POST['refresh']; ?>);
}, <?php echo (int)$_POST['refresh']; ?>);
Your values should be (30000, 60000, 120000), not (0, 1, 2). The POST field contains the value of the selected option, not the text.
Note: You should have been able to figure this out by checking the source of the resulting HTML document. The "1" ought to stick out like a sore thumb.
<select name="refresh" id="refresh">
<option value="30000">30000</option>
<option value="60000" selected>60000</option>
<option value="120000">120000</option>
</select>
window.setInterval(function(){
find_opt_schedule();
}, <?php echo (int)$_POST['refresh']; ?>);
And make sure you use:
<form action="yourscript.php" method="post" name="form" id="form">
And a submitbutton, or javascript:
<select name="refresh" id="refresh" onchange="form.submit()">
<input type="submit" value="Set refresh"/>
All together, with session storage:
<?php
session_start();
if( isset( $_POST['refresh']) ){
$_SESSION['refresh'] = (int) $_POST['refresh'];
}
?>
<script type="text/javascript">
window.setInterval(function(){
find_opt_schedule();
}, <?php echo isset($_SESSION['refresh'])?$_SESSION['refresh']:120000; ?>);
</script>
<form action="scheduler.php" method="post" name="form" id="form">
<select name="refresh" id="refresh" onchange="form.submit()">
<option value="30000">30000</option>
<option value="60000" selected="selected">60000</option>
<option value="120000">120000</option>
</select>
<input type="submit" value="Set refresh"/>
</form>
Use JQuery:
<html>
<body>
<select name="refresh" id="refresh">
<option value="30000">30000</option>
<option value="60000" selected>60000</option>
<option value="120000">120000</option>
</select>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function setInterval(refresh_rate)
{
window.setInterval(function(){
find_opt_schedule();
}, refresh_rate);
}
$(function(){
$('#refresh').change(function () {setInterval($(this).val());});
}
</script>
</body>
</html>
Erm... that's just plain HTML. All you need is to read it and adjust the timeout as needed:
<script>
(function() {
var start = new Date().getTime(),
selector = document.getElementById('refresh');
setInterval(function() {
// check if timer has run out
var now = new Date().getTime();
if( now-start > selector.value) {
find_opt_schedule();
start = now;
}
},1000);
})();
</script>

Categories