How I could populate the checked state of radio buttons depending on data loaded from the database?
I want to get data radio button for this form
<div class="col-md-4">
<label>
<input type="radio" name="menu_status" class="flat-red" value="1"> Enable
</label>
<label>
<input type="radio" name="menu_status" class="flat-red" value="0"> Disable
</label>
this my array result
{"menu_id":"00001","parent_id":"0 ","menu_name":"Dashboard","menu_title":"Dashboard","url":"dashboard_c","position_menu":"1","parent_status":"0","menu_status":"1","fa_icon":"fa-dashboard","type":"1"}
and I am pass that result through ajax like this
$.ajax({
url : "<?php echo site_url('cpanel/form_c/data_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="menu_id"]').val(data.id);
$('[name="parent_id"]').val(data.parent_id);
$('[name="menu_name"]').val(data.menu_name);
$('[name="menu_title"]').val(data.menu_title);
$('[name="url"]').val(data.url);
$('[name="order"]').val(data.position_menu);
$('[name="parent_status"]').val(data.parent_status);
//$('[name="menu_status"]').val(data.menu_status);
$('[name="fa_icon"]').val(data.fa_icon);
$('[name="type_form"]').val(data.type);
$.each (data, function (i, obj) {
$(':radio[name="menu_status"][value=' + obj.menu_status + ']').prop('checked', true);
});
/*if (data.parent_status===1) {
$('[name="menu_status"]').val("1").prop('checked',true);
} else {
$('[name="menu_status"]').val("0").prop('checked',true);
}*/
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Menu'); // Set title to Bootstrap modal title
},
Can someone help me to take the json data to select the appropriate choices?
var data = {"menu_id":"00001","parent_id":"0 ","menu_name":"Dashboard","menu_title":"Dashboard","url":"dashboard_c","position_menu":"1","parent_status":"0","menu_status":"1","fa_icon":"fa-dashboard","type":"1"}
console.log(data.menu_status)
$('input[name=menu_status][value='+data.menu_status+']').prop('checked', true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<label>
<input type="radio" name="menu_status" class="flat-red" value="1">Enable
</label>
<label>
<input type="radio" name="menu_status" class="flat-red" value="0">Disable
</label>
</div>
try this way, the check radio button will be equal to what data.menu_status value is
Looks like the radio button class is flat-red. You could simply use this one instead of going with complex selectors.
You could use a condition instead.
if (data.parent_status == 1) {
$('.flat-red').checked = true;
}
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!
On my page1.php I want to toggle the visibility of the page2.php.
I am using the following code:
<input type="radio" name="city" value="Barcelona" onclick="getPage2(this.value);"> Barcelona
<input type="radio" name="city" value="Manchester"> Manchester
I call the page2.php using this code:
function getPage2()
{
$.ajax({
type: "GET",
url: "page2.php",
success: function(result){
$("#show_results").html(result);
}
});
};
I want to show the page2.php only if the radio button is selected and show nothing (Hide it) if none of the radio buttons, or the 'Machester' radio button is selected.
UPDATE
I solved it. It was actually very easy.
<input type="radio" name="city" value="Barcelona" onclick="getPage2(this.value);"> Barcelona
<input type="radio" name="city" value="Manchester" onclick="getPage2(this.value);"> Manchester
I show and I hide the page2.php using this code:
function getPage2()
{
var var_name = $("input[name='city']:checked").val();
$.ajax({
type: "GET",
url: "page2.php",
success: function(result){
if(var_name == "Barcelona")
$("#show_results").html(result).show();
else
$("#show_results").html(result).hide();
}
});
};
Thank guys anyway.
You can use a JQuery selector for that :
$('input').click(function(){
$('input').show(); // Show all inputs
$(this).hide(); // Hide the clicked input
$.ajax({
type: "GET",
url: "page2.php",
success: function(result){
$("#show_results").html(result);
}
});
})
Of course, this works only for a page with those inputs only.
You should have classes or IDs to your radios to target them directly with the selector.
You will have something like this :
$('.radio-page').click(function(){ // ...
You could just load the hide-able content WITH the original page. That way you can avoid the ajax call.
<input class="radios" type="radio" name="city" value="Barcelona"> Barcelona
<input class="radios" type="radio" name="city" value="Manchester"> Manchester
<div id="content" style="display:none">Hide-able content</div>
And then just have the script make it appear when Barcelona is selected.
$("input[type='radio']").click(function()
{
if($(this).val() == "Barcelona") $("#content").show();
else $("#content").hide();
});
I've got the following form - 2 radio buttons in my A.php
<form action="form_processing.php" method="post" id ="myForm">
<div class="radio-inline">
<label>
<input type="radio" name="direction" id="direction" value="up" checked>Up
</label>
</div>
<div class="radio-inline">
<label>
<input type="radio" name="direction" id="direction" value="down" >Down
</label>
</div>
<input type="hidden" name="status" value="false">
<br/>
<button type="submit" name="sub" id="sub">Submit</button>
</form>
Then I've got the following jQuery A.js,
$('#myForm').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
Then on my form_processing.php I've got,
<?php
print_r($_POST);
?>
When I monitor my console, no matter what I seem to do, I always end up getting...
Array
(
[direction] => down
[status] => false
)
I've spent 2 days trying to figure out but.. can't find the cause of the problem why values of the radios are not updated....
To be more specific - works on IE10/11, doesn't work on chrome (tried to clear the browsing data etc etc..still not working)
Can someone plz guide me on where I went wrong?
Thanks alot,
The problem is that you are manually looping over all your inputs, regardless whether a radio button is checked or not. So when you are at the second radio button with the same name as the first, you overwrite your previous value.
You should probably let jQuery handle this by using:
data: $(this).serialize(),
You could of course manually check for the type of input and whether it is checked as well...
As I mentioned in my comment, you should only use an ID once per page as the ID has to be unique but that is not related to your problem.
i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/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.
}
});
});
});