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

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

Related

How to make jquery serialize ignores an input field in a div that toggles between hide and show

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!

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

how to hide/ show input box on radio button click event

I want to hide and show input field on radio button click event my HTML is
<input type="radio" id="abc" name="abc1" checked = "checked" value="Experienced" />
<label> Experienced </label>
<input type="radio" id="xyz" name="xyz1" checked = "checked" value="Fresher" />
<label>Fresher</label>
<input type="text" name="cardno" id="tyx" /><br />
<p > Number</p>
What I want is when radio button with value="Fresher" is clicked the input box name="cardno" should be hidden.
I tried to solve this by using jQuery but it is not working.
$(document).ready(function () {
$("input[name$='abc1']").click(function () {
var value = $(this).val();
if (value == 'Experianced') {
$("#tyx").show();
} else if (value == 'Fresher') {
$("#tyx").hide();
}
});
Can any body help me how to solve this?
name of your radio button should be same to check on click event or make array name of your radio button
like below code
<input type="radio" id="abc" name="abc1" checked = "checked" value="Experienced" />
<label> Experienced </label>
<input type="radio" id="xyz" name="abc1" checked = "checked" value="Fresher" />
<label>Fresher</label>
<input type="text" name="cardno" id="tyx" /><br />
<p > Number</p>
and then create function like
$(document).ready(function () {
$("input[name$='abc1']").click(function () {
var value = $(this).val();
if (value == 'Experianced') {
$("#tyx").show();
} else if (value == 'Fresher') {
$("#tyx").hide();
}
});
please reply if i can help you more..
change the spelling to Experienced
you used
if (value == 'Experianced')
Besides the typo in Experienced, try setting up a click event for each radio button:
$(document).ready(function() {
$('input[name="abc1"][value="Experienced"]').click(function() {
$("#tyx").show();
});
$('input[name="xyz1"][value="Fresher"]').click(function() {
$("#tyx").hide();
});
});
Note:
You can simplify your selectors to use ids with:
$('#abc')
and
$('#xyz')
Fix with:
$(document).ready(function () {
$("input[type='radio']").click(function () {
var value = $(this).val();
if (value == 'Experianced') {
$("#tyx").show();
} else if (value == 'Fresher') {
$("#tyx").hide();
}
});
});
Html:
<input type="radio" id="abc" name="jobtype" checked = "checked" value="Experienced" />
<label> Experienced </label>
<input type="radio" id="xyz" name="jobtype" checked = "checked" value="Fresher" />
<label>Fresher</label>
<input type="text" name="cardno" id="tyx" /><br />
<p > Number</p>
Radio buttons of same group should have same name
Js:
$(document).ready(function () {
$("input[name='jobtype']").click(function () {
var value = this.value;
if (value == 'Experienced') {
$("#tyx").show();
}
else{
$("#tyx").hide();
}
});
});

How to write an event for already selected radio button?

My code snippet for radio buttons is -
<input type="radio" name="isPush" id="isPushYes" <? if($isPush) {?>checked="checked"<?}?> value="<?= $isPush;?>" > <? echo "Yes"?></input>
<input type="radio" name="isPush" id="isPushNo" <? if(!$isPush) {?>checked="checked"<?}?> value="<?= $isPush;?>" > <? echo "No"?></input>
<table id="emailTable"><tr><td>...</td></tr></table>
The value of isPush will be 0 or 1. So one of my radio buttons will always be selected. And selecting either of the radio buttons initially is not in my hands.
Now, For the table, I want to set display: none when when second radio button is selected and set display: visible when first radio button is selected.
So which event should I put? I certainly can't put onclick.
You need to check the selected radio onload, as well as onchange. This means the table will be hidden to start with, if No is selected by default.
jsFiddle Demo
function checkRadio()
{
var tbl = document.getElementById("emailTable");
if(document.getElementById("isPushYes").checked)
{
tbl.style.display = "";
}
else
{
tbl.style.display = "none";
}
}
window.onload = function()
{
document.getElementById("isPushYes").onchange = checkRadio;
document.getElementById("isPushNo").onchange = checkRadio;
checkRadio();
}​
Another option is without the onload event, you set the display with PHP:
<table id="emailTable" <?php if(!$isPush) echo 'style="display:none"'; ?>><tr><td>...</td></tr></table>
i think this is what you want:
<label><input type="radio" name="myradio" value="1" checked="true" onchange="hideActive(this.name);" /> radio 1</label>
<label><input type="radio" name="myradio" value="2" onchange="hideActive(this.name);" /> radio 2</label>
<label><input type="radio" name="myradio" value="3" onchange="hideActive(this.name);" /> radio 3</label>
<script type="text/javascript">
function hideActive(radioGroupName) {
var all = document.getElementsByName(radioGroupName);
for(var n = 0; n < all.length; n++) {
if(true === all[n].checked) {
all[n].setAttribute('style', 'display: none;');
}
else {
all[n].removeAttribute('style');
}
}
}
hideActive('myradio');
</script>
if you support jquery try this
<label><input type="radio" name="myradio" value="1" checked="true" /> radio 1</label>
<label><input type="radio" name="myradio" value="2" /> radio 2</label>
<label><input type="radio" name="myradio" value="3" /> radio 3</label>
<script type="text/javascript">
jQuery(function() {
var all = jQuery('input[name=myradio]');
var change = function() {
all
.show()
.filter(':checked').hide();
};
all.change(function(){
change();
});
//call init
change();
});
</script>
You want to perform some action when the radio button is checked by the user, so you'll want to bind a handler for the onchange event.
you should write a javascript function that changes the display attribute and then call it in 2 places.
1- When the document loads.
window.onload = function () { javascript_function(); }
if you have JQuery you can do this:
$(document).ready(function(){
javascript_function();
)};
2- When there's a change in the radio button.
Either set a onchange="javascript_function" or use JQuery.
$(document).ready(function(){
javascript_function();
$("#radio_id").change(javascript_function());
)};
Its a test. Change it as like as you want
<script type="text/javascript">
function fnc(myid,otherid)
{
if(document.getElementById(myid).checked)
{document.getElementById(otherid).disabled='disabled';}
}
</script>
<input type="radio" name="isPush" id="isPushYes" onchange="fnc(this.id,'isPushNo')">
<input type="radio" name="isPush" id="isPushNo" onchange="fnc(this.id,'isPushYes')">
Onchange, for example (in JQuery):
$('input[name="isPush"]').change(function() {
// your code
});
Or:
<input onchange="myFunction();" type="radio" name="isPush" id="isPushYes" <? if($isPush) {?>checked="checked"<?}?> value="<?= $isPush;?>" > <? echo "Yes"?></input>
<input onchange="myFunction();" type="radio" name="isPush" id="isPushNo" <? if(!$isPush) {?>checked="checked"<?}?> value="<?= $isPush;?>" > <? echo "No"?></input>
I personally would look at onChange, this will catch occasions where the selected value changes. If doing this in jquery I'd do something like:
$('input[type=radio][name=isPush]').bind('change', function(e){
console.log('We had a change');
});
Note that if the item is dynamically added at all you should change bind to live.
here is the fidddle..
http://jsfiddle.net/vfuV5/2/
for example:
if($('input:radio[name="isPush"]:checked').val() == 'Yes') // used yes u can use 1 here
{
$('#emailTable').show();
}else{
$('#emailTable').hide();
}
$("input[name='isPush']").change(function() {
if($('input:radio[name="isPush"]:checked').val() == 'Yes') // used yes u can use 1 here
{
$('#emailTable').show();
}else{
$('#emailTable').hide();
}
});
OR
make a function
function checkRadioValue()
{
if($('input:radio[name="isPush"]:checked').val() == 'Yes') // used yes u can use 1 here
{
$('#emailTable').show();
}else{
$('#emailTable').hide();
}
}
Call this function on document.ready and onchange function
$(document).ready(function(){
checkRadioValue();
$("input[name='isPush']").change(function() {
checkRadioValue();
});
})

How to add new content when a checkbox is clicked?

I made a design with ajax, jquery, mysql and checkbox in php. It is like that :
There is box with checkboxes. And there is another box which is empty. When you checked a checkbox in first box, information about that checkbox will be displayed in empty box. I did it and work good.But when you clicked another checkbox, information about first you clicked dissappear and only current selection is displayed. That is to say, I want to add new selection on old ones. Also how can I delete information in second box when I unchecked a checkbox. Thank you.
Here is HTML code :
<div id="first_box">
<label class='checkbox'>
<input type='checkbox' id=1>
First checkbox
</label>
<label class='checkbox'>
<input type='checkbox' id=2>
Second checkbox
</label>
<label class='checkbox'>
<input type='checkbox' id=3>
Third checkbox
</label>
</div>
<div id="second_box"> </div>
Here is jquery code :
$(document).ready(function() {
$("#first_box input:checkbox").change(function() {
if($(this).is(":checked")) {
$.post("/here/is/url", { strID:$(this).attr("id"), strState:"1" },
function(data) {
$("#second_box").html(data);
});
} else {
$.ajax({
url: 'here/is/url/',
type: 'POST',
data: { strID:$(this).attr("id"), strState:"0" }
});
}
});
});
Here is the php code for ajax request :
$strID = $_POST['strID'];
$strState = $_POST['strState'];
if ($strState) { //if checkbox is clicked
//I fetch data about checkbox which is clicked
$infos = $this->info_model->get_info_from_checkbox_id($strID);
foreach ($infos as $info) {
echo "<label class='checkbox'>
<input type='checkbox'>".$info->information .
"</label>";
}
} else { // if it is unchecked
// I do not know how to delete
}
I want to add new selection on old ones.
you can use append() instead of html() which replaces the content:
$("#second_box").append(data);
how can I delete information in second box when I unchecked a checkbox.
you can use empty() which removes the contents of the selected element:
$("#second_box").empty();
Alternatively, you could do more on the client-side. See here for a demo.
<div id="first_box">
<label class='checkbox'>
<input data-url="url1" data-id="1" type="checkbox"> First checkbox
</label>
<label class='checkbox'>
<input data-url="url2" data-id="2" type="checkbox" > Second checkbox
</label>
<label class='checkbox'>
<input data-url="url3" data-id="3" type="checkbox"> Third checkbox
</label>
</div>
<div id="second_box"></div>​
JavaScript:
$(document).ready(function() {
$("#first_box input:checkbox").change(function(e) {
var $this = $(this);
if (already_loaded()) {
update_visibility();
} else {
load();
}
// END -- Functions
function already_loaded() {
return $this.data("loaded");
}
function is_loading() {
return $this.data("loading");
}
function load() {
if (!is_loading()) {
$this.data("loading", true);
var id = $this.data("id");
$.post("url", { // or use $this.data("url") if you want individual URLs
strId: id
}, function(data) {
$this.data("loaded", true);
$this.data("is_loading", false);
$("#second_box").append(data);
update_visibility();
});
}
}
function is_checked() {
return $this.is(":checked");
}
function update_visibility() {
var $info = $("#info-" + $this.data("id"));
if (is_checked()) {
$info.show();
}
else {
$info.hide();
}
}
});
$("#first_box input:checkbox").data("loaded", false);
$("#first_box input:checkbox").data("loading", false);
});​

Categories