Radio buttons result show on body onload in show/hide div - php

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.
}
});
});
});

Related

JSON : Select Radio button base on response

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;
}

Custom php form validation

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();
}
});

Submit checkbox ID and textfield value without refreshing browser using Ajax

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/

How to debug using firebug and show the value of radio button

I have radio buttons as shown below.
<div id="lensType">
<input type="radio" name="design" style="vertical-align: middle" value="1"/>
<label for="design">Single Vision</label><br/>
<input type="radio" name="design" style="vertical-align: middle" value="2" />
<label for="material" >Accommodative Support</label><br/>
<input type="radio" name="design" style="vertical-align: middle" value="3"/>
<label for="design">Bifocal</label> <br/>
<input type="radio" name="design" style="vertical-align: middle" value="4" />
<label for="material" >Varifocal (Intermediate/Near)</label><br/>
<input type="radio" name="design" style="vertical-align: middle" value="5"/>
<label for="material" >Varifocal (Distance/Near)</label>
</div>
I am making a dynamic select. I have my javascript code that post the value . It seems the supplier value is now posted. Below is the code for my script.
$(document).ready(function(){
function populate() {
fetch.doPost('getSupplier.php');
}
$('#lensType').change(populate);
var fetch = function() {
var counties = $('#county');
return {
doPost: function(src) {
$('#loading_county_drop_down').show(); // Show the Loading...
$('#county_drop_down').hide(); // Hide the drop down
$('#no_county_drop_down').hide(); // Hide the "no counties" message (if it's the case)
if (src) $.post(src, { supplier: $('#lensType').val() }, this.getSupplier);
else throw new Error('No source was passed !');
},
getSupplier: function(results) {
if (!results) return;
counties.html(results);
$('#loading_county_drop_down').hide(); // Hide the Loading...
$('#county_drop_down').show(); // Show the drop down
}
}
}();
populate();
});
Php code :
<?php
if(isSet($_POST['supplier'])) {
include 'db.php';
$stmt = $mysql->prepare("SELECT DISTINCT SupplierBrand FROM plastic WHERE HeadingNo='".$_POST['supplier']."'");
$stmt->execute();
$stmt->bind_result($supplierBrand);
while ($row = $stmt->fetch()) : ?>
<option value="<?php echo $supplierBrand; ?>" width="100px"><?php echo $supplierBrand; ?></option>
My problem is when I debug I notice there is no value passed to the php script and this makes the select empty. I have tried to trace or debug by having firebug output the console.log and failed in this regard.
Please assist with this code which is meant to show a dynamic list from a radio button selection.
for debugging:
$('input[name="design"]').change(function(){
console.log($('#lensType').find("input:radio[name ='design']:checked").val());
});
else:
$('#lensType').find("input:radio[name ='design']:checked").val();
instead of
$('#lensType').val()
and you probably want to wrap it witg a changed function, since onload no design is selected:
$(document).ready(function(){
$('input[name="design"]').change(function(){
var design = $('input[name="design"]:checked').val();
function populate() {
fetch.doPost('getSupplier.php');
}
$('#lensType').change(populate);
var fetch = function() {
var counties = $('#county');
return {
doPost: function(src) {
$('#loading_county_drop_down').show(); // Show the Loading...
$('#county_drop_down').hide(); // Hide the drop down
$('#no_county_drop_down').hide(); // Hide the "no counties" message (if it's the case)
if (src) $.post(src, { supplier: design }, this.getSupplier);
else throw new Error('No source was passed !');
},
getSupplier: function(results) {
if (!results) return;
counties.html(results);
$('#loading_county_drop_down').hide(); // Hide the Loading...
$('#county_drop_down').show(); // Show the drop down
}
}
}();
populate();
});
});
In your javascript you are getting the value of the div, not the radio button:
$('#lensType').val() <--- change that
To something like this:
$("#lensType input:radio[name='design']:checked").val()

Jquery Ajax based search

I want to do the search using ajax jquery js, for that I have taken this piece of code from here:-
Now i have some issues, I have this Javascript code:-
<script language="JavaScript" type="text/javascript">
<!--
function searchuser(cv) {
$("#SearchResult").html('<img src="loader.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#SearchResult").html(data).show();
});
}
//-->
</script>
My Form:-
<label>
<input onClick="generatenew();" type="radio" name="search_option" value="code" id="search_option_0">
Customer Code</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="company" id="search_option_1">
Customer Company</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="name" id="search_option_2">
Customer Name</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="email" id="search_option_3">
Customer Email</label>
This is my search textbox
<input type="text" name="searchuser_text" id="newInput" size="25" maxlength="25" class="inputbox MarginTop10">
This is my search button
<input onclick="javascript:searchuser('con1');" class="Button" name="search_user_submit" type="button" value="Search">
This is my Display Area :-
<div id="SearchResult">My default content for this page element when the page initially loads</div>
Now i want to know on click of button i am sending a data i.e. con1. I want to send two data to the searchuser function, one the selected option button value and the another one is the text in the textbox. After sending both the data to the function how will i get the data in the function? Do i need to change the function searchuser(cv) to function searchuser(cv, cvtwo).
Also while the $.post(url, {contentVar: cv} ,function(data) is sending only one data to the php file, how can i send both the data i.e. cv and cvtwo to the php file?
First of all you can modify the search function to something like this
$("input[name='search_user_submit']").click(function(){
var cv = $('#newInput').val();
var cvtwo = //similar to above
var data = 'cv='+ cv + '&cvtwo='+cvtwo; // sending two variables
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {contentVar: data} ,function(data) {
$("#SearchResult").html(data).show();
});
});
Don't use inline functions, you can do it easily with jQuery's native bind functionality:
// Search when you click on submit
$(document).on('click', '.submit_button', function(){
search('click_button');
});
// Search when you press enter
$(document).on('keypress', "#searchString", function(e){
var c = (e.keyCode ? e.keyCode : e.which);
if(c == 13) {
search('pressed_enter');
}
});
You can therefore collect the button value and pass it through to your search function:
function search(button_value) {
$("#myDiv").html('<img src="loader.gif"/>').show();
$.post("elements/search-user.php", { search_value: $('#newInput').val(), button_value: button_value} ,function(data) {
$("#SearchResult").html(data).show();
});
}
What you're doing is send off the form with two $_POST variables: one is the search string you've inputted in to the search box (called search_value) and the other is the button value.

Categories