I have a form which is submitted on option change. It is connected to the database. So everytime I submit the form, the page reloads and the value is selected (the value is now saved as "car" in the database).
<form class="cars" id="carSelect" name="car" action="index.php" method="get">
<select onchange='this.form.submit()'>
<option <?php if ($row['car'] == Volvo ) echo 'selected'; ?> value="volvo">Volvo</option>
<option <?php if ($row['car'] == Saab ) echo 'selected'; ?> value="saab">Saab</option>
<option <?php if ($row['car'] == Opel ) echo 'selected'; ?> value="opel">Opel</option>
<option <?php if ($row['car'] == Audi ) echo 'selected'; ?> value="audi">Audi</option>
</select>
</form>
when the form is submitted and the selected option is Volvo, a modal (I am using the bootstrap modal) should appear. This is the bootstrap modal code, which opens the modal when I click on the "openBtn" Button.
Volvo
<div id="modal-content" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Volvo</h3>
</div>
<div class="modal-body">
<p>
<input type="text" id="txtname" />
</p>
</div>
<div class="modal-footer">
cancel
save
</div>
</div>
</div>
</div>
The bootstrap modal script for opening the modal with a button:
$('#openBtn').click(function () {
$('#modal-content').modal({
show: true
});
});
So here is my approach:
$(window).load(function(){
if($(.cars option:Volvo).is(':selected')){
$('#modal-content').modal({
show: true
});
}
});
But my code is not working. The other problem is, the modal should only appear if I selected "Volvo". Not everytime the page is loaded. But I do not know how I can detect that the form was submitted before the page is loaded.
When you want the selected option you have to take it from the select DOM element. So you would start with giving it an ID.
<select onchange='this.form.submit()' id="carSelect">
Then you can get the currently selected value and use it as condition.
$(window).load(function(){
var value = $( "#carSelect option:selected").val();
if(value == 'volvo'){
$('#modal-content').modal({
show: true
});
}
});
I have the correct solution that you have been waiting for.
Please look at this code :
function myFunction() {
var option_value = document.getElementById("numbers").value;
if (option_value == "3") {
alert("Hai !");
}
}
<!DOCTYPE html>
<html>
<head>
<script>
// Add the above javascript code here !
</script>
</head>
<body>
<select id = "numbers" onchange = "myFunction()">
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">Click me !</option>
</select>
</body>
</html>
First, you can check the selected value in select option. Select adds the :selected property to the selected option which is a child of the dropdown.
$(document).ready(function(){
$("#select").on('change', function(){
if($(this).find(":selected").val()=='xyz'){
//alert($(this).find(":selected").val());
$('#modal-content').modal({
show: true
});
}
});
});
I know this question is very old, but for those who may find it like I did, I wanted to share a small adaptation I did, so if I have one modal per select option, I don't need to check every and each of the possibilities:
$(document).ready(function(){
$("#myModalSelector").on('change', function(){
var selected = $(this).find(":selected").val();
$('#' + selected ).modal({
show: true
});
});
});
Try this:
<select onchange='funMyModel(this.value)'>
function funMyModel(val)
{
if(val=="Volvo"){
$('#modal-content').modal({
show: true
});
}
}
Related
Bellow shown code does these things
when i select Scholership Programs from select list the div element with class="mystaff_hide mystaff_opt1" will be shown
and then i select Family Income now div with class="mystaff_hide mystaff_opt2" will be shown. Now both are there on my window.
Up to this the code works fine
What i want is after submission of my form i want both of them are must be there on my window
<div class="row">
<div class="col-md-6 col-sm-6 pull-left">
<div class="form-group">
<legend>Options to Search</legend>
<select class="form-control firstdropdown" name="sel_options" id="mystuff">
<option>Select Options</option>
<option value="opt1">Scholership Programs</option>
<option value="opt2">Family Income</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt1">
<div class="form-group">
<label for="LS_name">Scholarship</label>
<select class="form-control" name="LS_name[]" id="LS_name" multiple="multiple">
<option value="opt1">Scholership1</option>
<option value="opt2">Scholership2</option>
</select>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt2">
<div class="form-group">
<label for="Family Income">Family Income</label>
<select multiple class="form-control" name="FamilyIncome[]" id="FamilyIncome">
<option value="opt1">Family Income1</option>
<option value="opt2">Family Income2</option>
</select>
</div>
</div>
This is my script
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/js/jquery.multi-select.min.js"></script>
<script>
$( document ).ready(function() {
$('.mystaff_hide').addClass('collapse');
$('#mystuff').change(function(){
var selector = '.mystaff_' + $(this).val();
$(selector).collapse('show');
});
});
</script>
After lot of search i got this code which is shows only recent related selected option's div
<?php if(isset($_POST['sel_options']) &&
!empty(isset($_POST['sel_options']))){
?>
<script>
var selected_option = "<?php echo $_POST['sel_options']; ?>";
var selector = '.mystaff_' + selected_option;
//show only element connected to selected option
$(selector).collapse('show');
</script>
<?php } ?>
Take a look at localStorage or sessionstorage to store information about the state of webpage and read them after reload to restore the UI state
Example:
Localstorage
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Sessionstorage
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Or you may want to use AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
As you are using jquery, you may want to look at using Ajax in jquery.
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
hello i want to display data of business3's data according to business2's and business2's data according to business1's dropdown list but on change() of business1 i got data in response but I didn't get second on change() in dropdown list.
<!-- ajax code for first business starts here -->
<script>
$(document).on('change', 'select.Business1', function(){
var business1 = $('select.Business1 option:selected').val();
alert(business1);
var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url('client_area/select_business_sub_cat'); ?>',
success : function (data){
$('#business2').empty();
$('#business2').append(data);
}
});
});
</script>
<!-- ajax code for first business ends here -->
// This script is not working. i can't find second change event.
<!-- ajax code for second business starts here -->
<script>
$(document).on('change','#business2',function(){
alert('Change Happened');
});
</script>
<!-- ajax code for second business ends here -->
I have tried with live() method also so alert called on first dropdown selection and then the ajax request calls so second drop down fills (Alternate for second script) ,
<script>
$(document).live('change', '#business2', function() {
alert('Change Happened');
});
</script>
Model function
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->db->query("select category.id,subcategory.* From category LEFT JOIN subcategory ON category.id = subcategory.category_id where category.id = '$business1'");
$row_cat1 = $result_sub_cat1->result();
$data = array(
'id' => $row_cat1['0']->id,
'name' => $row_cat1['0']->name
);
echo "<option value='" . $row_cat1['0']->id . "'>" . $row_cat1['0']->name . "</option>";
// return $this->output->set_output($data);
}
View --
<div class="form-group">
<label>Business 1</label>
<select name="txtBusiness1" id="" style="height: 30px;width: 100%;" class="Business1">
<option value=""> Select Business </option>
<?php
$result_cat1 = $this->db->query("select * from category");
$row_cat1 = $result_cat1->result();
?>
<?php foreach($row_cat1 as $item){ ?>
<option value="<?php echo $item->id; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
</div>
<div class="form-group">
<label>Business 3</label>
<select name="txtBusiness4" id="business3" style="height: 30px;width: 100%;" class="Business3">
<option value=""> Select Business3 </option>
<?php echo $abc; ?>
</select>
</div>
Maybe that's because by calling $('#business2').html(data); you remove the event handlers, from jQuery documentation: http://api.jquery.com/html
When .html() is used to set an element's content, any content that was
in that element is completely replaced by the new content.
Additionally, jQuery removes other constructs such as data and event
handlers from child elements before replacing those elements with the
new content.
One option would be to use empty and append like this
$('#business2').empty();
$('#business2').append(data);
instead of $('#business2').html(data);
The Script which is not working for you !!!
<script>
$(document.body).on('change','#business2',function(){
alert('Change Happened');
});
</script>
Try this in place of the above script :
$(document).on("change", "#business2", function(){
alert('Change Happened');
});
this is my test form,in this form i want to apply change function and keyup functions,but it doesnt work
<form>
<div id="main" class="group1">
<div>
<label>Choose group</label>
<select name="group " id="sktest">
<option value="group1">Group 1</option>
<option value="group2">Group 2</option>
<option value="group3">Group 3</option>
</select>
</div>
<div class="group1_opts">
<label>G1 option </label><input id="sk" type="text" name="opt1">
</div>
<div class="group1_opts group2_opts">
<label>G1/G2 option</label><input id="sk" type="text" name="opt2">
</div>
<div class="group2_opts group3_opts">
<label>G2/G3 option</label><input id="sk" type="text" name="opt3">
</div>
<div class="group3_opts">
<label>G3 option</label><input id="sk"type="text" name="opt4">
</div>
</div>
</form>
</div>
<?php get_footer(); ?>
<script
src="http://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$("#sktest").change(function(){
alert('ok');
});
$("#sk").keyup(function(){
alert('ok');
});
</script>
i am trying to alert messages but it doesent work .please help me/...
First of all Id should be unique. So in case you needed to bind same function with multiple elements, use class then.
Second, put your js function inside $(document).ready
I checked when putting your function in $(document).ready() plus if you have mutliple ids it will fire only for the first element.
It has nothing to do with wordpress
$(document).ready(function(e)
{
alert('jQuery loaded');
$("#sktest").change(function(){
alert('ok');
});
$("#sk").keyup(function(){
alert('ok');
});
})
Hi #Pankaj Waghmare user JQuery instead of $.
Example : JQuery(document).ready();.
Hope this helps u.
I have an index page with three buttons at the top. On the click of each button a php file is loaded into the main div. One of these buttons loads a form that users fill out and submit. On submitting of the form I need it to not refresh the page and to load the resulting data into a div on the form page...not the main div.
If I load the form page on it's own (ie, not by clicking on the button, but just typing in the address of the form itself)...everything works fine. The form validation works, it submits without a refresh and the resulting data is returned into the results div on the form.
However, I load the index page and click on the button to load the form. The form loads correctly, but when I click submit it just refreshes the page...which causes the form to disappear since the div into which it is loaded is originally hidden. Also, the form doesn't validate and doesn't execute the php action.
Again, the form and its associate php work perfectly on their own. The issue only comes up when I load the form in the index page. So I'm assuming that this issue has something to do with me loading it into a div on the index page. Any help would be greatly appreciated.
Index code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="header">
<center><h2>OMS Tutoring Database</h2></center>
</div>
<div id="navbar">
<center>
<button class="navbutton" id="buttonview" type="button">View Tutoring Lists</button>
<button class="navbutton" id="buttonadd" type="button">Add Students</button>
<button class="navbutton" id="buttonadmin" type="button">Admin</button>
</center>
<br>
</div>
<div id="content"></div>
<script>
$(document).ready(function() {
$('#buttonview').click(function(){
$('#content').load('tutoring.php', function(){
});
});
$('#buttonadd').click(function(){
$('#content').load('addtest.php', function(){
});
});
$('#buttonadmin').click(function(){
$('#content').load('admin.php', function(){
});
});
});
</script>
</body>
</html>
Form Code
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addstudent").validate({
debug: false,
rules: {
studentid: "required",
teacher: "required",
assignment: "required",
date: "required",
},
messages: {
studentid: "Please enter the student's ID number.",
teacher: "Please enter your name.",
assignment: "Please select a tutoring assignment.",
date: "Please select a day.",
},
submitHandler: function(form) {
$.ajax({
url: 'add.php',
type: 'POST',
data: $("#addstudent").serialize(),
success: function(data) {
$("#studentid").val("");
$('#studentid').focus();
$("#results").empty();
$("#results").append(data);
}
});
return false;
}
});
});
</script>
</head>
<title>OMS Tutoring - Add Student</title>
<body>
Use this form to add students to the tutoring list.
<p>
<div style="float:left;width:100%;margin-bottom:10;">
<div>
<form name="addstudent" id="addstudent" action="" method="post">
<fieldset><legend>Add student to tutoring list</legend>
<div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>
<div><label for="day">Date</label><select name="date" id="date">
<option value="">Please select a day</option>
<option value="mon">Monday <? echo $monday; ?></option>
<option value="tue">Tuesday <? echo $tuesday; ?></option>
<option value="wed">Wednesday <? echo $wednesday; ?></option>
<option value="thu">Thursday <? echo $thursday; ?></option>
<option value="fri">Friday <? echo $friday; ?></option>
</select></div>
<div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
<option value="">Please select an assignment</option>
<option value="att">Activity Time</option>
<option value="acc">ACC</option>
<option value="tech">ACC Tech </option>
<option value="ast">After School</option>
</select></div>
<div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>
<input type="submit" name="submit" value="submit">
</fieldset>
</form></div></div>
<div id="results" style="margin-left:4;width:350;"><div>
</body>
</html>
Form processing php code:
<?php
$mysqli = new mysqli('localhost', 'xxx', 'xxx', 'xxx');
$studentid = $_REQUEST['studentid'];
$day = $_REQUEST['date'];
$assignment = $_REQUEST['assignment'];
$teacher = $_REQUEST['teacher'];
$dayquery = $mysqli->query("SELECT date FROM days WHERE day='$day'");
$dayresult = $dayquery->fetch_array();
$date = array_shift($dayresult);
$timestamp = date('Y-m-d H:i:s');
$mysqli->query("INSERT INTO assign (id, assignment, assignteacher, date, timestamp)
VALUES ('$studentid', '$assignment', '$teacher', '$date', '$timestamp')");
$namequery = $mysqli->query("SELECT first, last FROM students WHERE students.id='$studentid'");
$nameresult = $namequery->fetch_array();
echo $nameresult['first'].' '.$nameresult['last'].' successfully added.';
$teacherquery = $mysqli->query("SELECT assignteacher FROM assign WHERE id='$studentid' AND date='$date'");
$rowcount = $teacherquery->num_rows;
if ($rowcount > 1) {
while ($row = $teacherquery->fetch_array()) {
$teachernames[] = $row[0];
}
$teachers = implode(', ', $teachernames);
echo '<br><br>Caution: '.$nameresult['first'].' '.$nameresult['last'].' has already been added by the following teachers: '.$teachers.'. ';
echo 'They may have precedence.';
}
else {
}
$alreadyadded = $mysqli->query("SELECT assign.id, students.first, students.last, assign.assignment, assign.assignteacher FROM assign
LEFT JOIN students
ON assign.id=students.id
WHERE assign.date='$date' AND assign.assignteacher='$teacher'
ORDER BY assign.assignment ASC, students.last ASC");
echo '<br><br><br>You already have the following student(s) assigned to tutorials on this day';
echo '<table border="1">';
while ($row = $alreadyadded->fetch_array()) {
echo '<tr><td>'.$row['id'].'</td><td>'.$row['first'].'</td><td>'.$row['last'].'</td><td>'.$row['assignment'].'</td></tr>';
}
?>
When you load the form into your page using the load method, most browsers delete the <head> tag.
As from the jquery website:
During this process, browsers often filter elements from the document
such as <html>, <title>, or <head> elements. As a result, the elements
retrieved by .load() may not be exactly the same as if the document
were retrieved directly by the browser.
So, include your javascript in the main page instead of in the form page, or manually add the javascript to your main page dynamically.
im trying to make a simple form which have a select menu with clone and remove button and once any of those select menus changed it must post the form using .Ajax call .
its working but have some issues
HTML
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" id="lang" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>
JS
$(function(){
var counter = 1;
$(".clone").click(function(){
$('#lang').clone().appendTo('#fileds');
counter++ ;
});
$(".remove").click(function(){
if (counter > 1) {
$('#lang:last').remove();
counter-- ;
}
});
$('.lang').change(function(){
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});
it have 2 issues
first one when i click the remove button it remove the original select menu first then the cloned one and keep the last cloned one what i need is to remove the cloned menus first and keep the original one
second issue its submit form only when original menu changed what i need is to submit form whenever any menu changed original or cloned.
below is the PHP code from the action PHP page its something simple just to show result
PHP
<?php
print_r ($_POST['lang']);
?>
Thanks
HTML:
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>
Note: Id of the field has been removed.
JS:
$(function(){
$(".clone").click(function(){
// clone(true) will clone the element with event handlers intact.
$('.lang').last().clone(true).appendTo('#fileds');
});
$(".remove").click(function(){
var selects = $('.lang');
if (selects.length > 1) {
selects.last().remove()
}
});
$('.lang').change(function(e){
// console.log(e)
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});
Demo:
http://jsfiddle.net/kFB5j/1/