jquery change function on radio button is working properly when they are part of html body i.e when they have written in html body, but when they loaded through ajax request change function not works. My code is-
html code
<form>
<select id="sel" name="sel">
<option value="">Select Type</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="load"></div>
<label id="change">--</label>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.radi').change(function(){
console.log( "radio clicked!" );
$('#change').html("Loaded2: ");
});
$("#sel").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax ({
type: "POST",
url: "faculty.ajax_load.php",
data: dataString,
cache: false,
success: function(html){
$("#load").html(html);
console.log( "radio loaded" );
}
});
});
});
</script>
ajax_load.php is:-
<?php
echo '<input class="radi" type="radio" name="sect" value="P" id="p"/>
<input type="radio" class="radi" name="sect" value="A" id="a" checked="checked"/>';
?>
Now the problem is radio buttons are appear but when I click them change is not shown on console and label. Please help, where I am doing mistake.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
As you are loading using ajax call.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
As per your code
$("#load").on('change', '.radi', function(){
console.log( "radio clicked!" );
$('#change').html("Loaded2: ");
});
Related
I have the following 3 checkboxes which are populated from a php database. I need assistance with JQUERY that once any select box is changed the value is posted to a php file and able to return a response through JQUERY.
Each select box should be standalone to only send that checkbox value & name to the PHP file.
I have the below JQUERY to start with to send the first checkbox but am getting no response back.
What amendments need to be made to the JQUERY to receive the input of the other checkboxes and then send the data correctly?
The php file will simply have echo "WHAT EVER THE RESPONSE IS" using if statements.
Any help grately appreciated with thanks.
$(document).ready(function() {
$('select.person-1').change(function() {
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $('select.person-1').val(),
changeCol1: $('input[name$="changeCol1"]').val()
},
dataType: "html",
},
success: function(data) {
var a = data.split('|***|');
if (a[1] == "update") {
$('#msg').html(a[0]);
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name='person-1' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol1' value='person-1'>
<select name='qty' class='marshal-select'>
<option value='1'>1</option>
</select>
<input type='hidden' name='changeCol2' value='qty'>
<select name='person-2' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol3' value='person-2'>
The selectors you've used are incorrect for the HTML displayed. .person-1 is a class selector, yet the select elements have that value in their name.
In addition your success property is outside the options object of the $.ajax call - it needs to be inside.
You can fix this issue and DRY up the code to make it more extensible by removing the hidden fields, hooking the change event handler to the common marshal-select class on all the select elements, and by using the name attribute of the select elements to fill the changeCol property of the data you send in the AJAX request. Try this:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
// in your AJAX request...
let data = {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
};
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="person-1" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
<select name="qty" class="marshal-select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="person-2" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
As an aside, the logic in the success handler implies that you're returning plain text and then hacking the string around using split(). Do not do this. Return a serialised data structure, such as JSON instead. This is more extensible and makes the code far more robust.
Update:
With your code you have added could you just add an edit where how you would receive a response ideally I want a positive response to show the msg div and where you would call the php file?
Sure, here you go:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
},
dataType: "html",
success: function(data) {
// assuming a JSON response:
if (data[1] === 'update') {
$('#msg').html(data[0]).show();
}
}
});
});
});
Note that I've not included the PHP which would generate the JSON response as I'm not a PHP dev. I'm sure there are lots of topics covering that if you search.
I have some drop downs looks like this in my HTML form:
<form name="fee" method="POST" action="">
<p><span class="title">Number of artists:</span>
<select name="Number">
<option value="" rel="none" selected disabled>Please select an option..</option>
<option value="one" rel="one_art">One artist only</option>
<option value="more" rel="more_arts">More than one artists</option>
</p>
A table of summery will be generated after I click the submit button.
<input type="submit" value="Calculate">
My question is: Whenever I click the button, the previously selected option will be reset. And only the summery show up at the end of the page. Is there a way to output the summery on the same page without the previously selected option gets cleared?
Thanks in advance!!
I think your best option is to use AJAX POST to post the form data, and JQuery to keep the same option selected:
$(document).ready(function() {
$("#fee").on('submit',(function(e) {
e.preventDefault();
var selectedOption = $( "#Number option:selected" ).text();
$.ajax({
url: "here put the url to the php page handling your form data",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function ()
{
$("#Number").val(selectedOption);
}
});
}
});
I have a jQuery Ajax problem.
I have a select tag with options of courses, the select holds div id="course". I have a button with id of "go" and an empty div with id of "courseInfo". I need to make it so that when a course number is selected, the teacher name in my php file that goes with it is displayed on the page. I have all my Ajax written, everything is linked, but it wont work and no error when I debug.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
Form:
<form action="" method="post">
<select name="course" id="course">
<option value="420-121">420-121</option>
<option value="420-122">420-122</option>
<option value="420-123">420-123</option>
<option value="420-221">420-221</option>
<option value="420-222">420-222</option>
<option value="420-223">420-223</option>
<option value="420-224">420-224</option>
</select>
Select a course to see the course name and teacher assigned<br><br>
<input type="button" id="go" value="go!">
</form>
<br><br>
<div id="courseInfo"></div>
Assuming that the PHP side is working properly, the code below should fix the issue.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
console.log(file);
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
You miss the = in var file.
Yours was
var file = "Course.php?course"+$("#course").val();
It should be
var file = "Course.php?course="+$("#course").val();
This is my html code
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
and my database table is like this
courseId courseName courseCredits
1 Diploma in Computing 5
So my request is, if i change the value in the 'select' the 'courseCredits' value should appear in the textbox. for this how can i write jquery code?
"Ajax with Jquery" is what your are looking for. It will work like this:
the user chooses an option from the select box
you submit via Javascript the chosen option to a PHP script
the php script fetches the data from the database
the php script returns the result as json encoded data
there is a callback function in your javascript code. This js code will manipulate the HTML in whatever way you want, e.g. "add the option to your select box"
There are tons of tutorials on how to do Ajax requests in detail, e.g. http://openenergymonitor.org/emon/node/107
Check out one of those tutorials - eventually you will want to update your question so that it becomes a bit more specific? :-)
it is good practice to seperate you html from scripts so i would like to change :
<select name="course" id="course" onchange="valuesOfAll(this.value)">
to
<select name="course" id="course" >
then my script will be following (hoping you add reference of latest jquery )
<script>
$(document).ready(function(){
//bind change event once DOM is ready
$('#course').change(function(){});
getResult($(this).val());
});
function getResult(selectedValue){
//call ajax method to get data from database
$.ajax({
type: "POST",
url: url,//this should be replace by your server side method
data: "{'value': '"+ selectedValue +"'}", //this is parameter name , make sure parameter name is sure as of your sever side method
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (Result) {
alert(Result.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
use $.post.. (ajax or get)... i am using post here....go through the docs if you want to read more about jquery post..
javascript
function valuesofAll(val){
$.post('test.php',{data:val},function(result){
$('#course_credits').val(result.coursecredit)
}, "json"); //expect response as json..
}
test.php
$data=$_POST['data']; //this is the value posted
//make you query in db get result..
$courseCredits= $row; //db returned courseCreadit value
echo json_encode(array('coursecredit'=>$courseCreadits)); //send response as json
this will helps you .....
<script>
function valuesOfAll(value)
{
var base_url="http://.../../hello.php";
var ip=new Object();
ip.course=value;
var inputParam=JSON.stringify(ip);
var module="getcourseCredits"
$.ajax({
type: "POST",
url: base_url,
data: {coursevalue:inputParam,module :module},
dataType: "json",
success: function(msg)
{
$("#course_credits").val(msg.credit);
}
});
}
</script>
<body>
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
</body>
In your PHP file
<?php
if(isset($_POST['module']))
{
if($_POST['module']=='getcourseCredits')
{
$val=json_decode($_POST['coursevalue'],true);
$courseval=$val['course'];
// do the connectivity and query here and finally echo the result as json format that is the response to the ajax call
.
.
.
.
}
}
?>
I have a MySQL table which looks like this:
ID OPTION
1 First
2 Second
The user sees the following:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
</select>
</div>
I would like the user to have the option to insert into the table, as follows:
<div id="add">
<input type="text" name="newOption" placeholder="Your own option">
<input type="button" value="Add">
</div>
It would then select their newly-added option:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3" selected>Third</option>
</select>
</div>
As the above code is part of a page which contains other form elements the page can't be reloaded, otherwise the data they've already typed will disappear. So I'd like to use jQuery.
EDIT: I have tried the following but it adds rows twice, sometimes even four times, for reasons I cannot fathom!
$("#button").click(function(){
var test = $("#<?php echo $selectName; ?>").val();
var dataString = 'select=<?php echo $select; ?>&selectName='+ test;
$.ajax({
type: "POST",
url: "optionAdd.php",
data: dataString,
cache: false,
success: function(html){
$("#<?php echo $select; ?>List").load("optionList.php?select=<?php echo $select; if ($_GET[required] == "no") { echo "&required=no"; } ?>");
}
});
});
The reason for the PHP above is I want to use multiples of this code on the same form and so I'm using GET to select the options, as it were.
You would need to send an AJAX request to server with the new data and get an ID returned for this new option. Once the ID is received you can create the option with the new ID as value and the user defined text
$('#add button').click(function(){
/* get value from previous input*/
var newOpt=$(this).prev().val();
/* make AJAX "POST" request*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( newId ){
/* ajax successfully completed, add new option*/
$('#options select').append('<option value="'+ newId +'">'+newOpt+'</option>');
});
return false; /* prevent browser default handling of button click*/
})
At server receive the data as you would a form field with name="newOption" ie $_POST['newOption'] and send back a new ID as text
Alternatively you could send back all the options as html in sort order you want and replace all the options in the select.
/* ajax to replace all options with html from server*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( response ){
/* ajax successfully completed, add new option*/
$('#options select').html( response);
});
I would suggest using jQuery AJAX to call a PHP Script to store the new option to the database, that returns the new ID and the given option name on success and then add the new entry to the <select> using Javascript.