PHP/Javascript ajax call - get old data before onchange function - javascript

I have an select input field, and i have an onchange function. The table shows the value on the selected value, if nothing is selected, it should show all data. I want to know if it possible to get the value of that select field before the onchange happens? So, the value before the change.
I looked on the internet, but nothing helps.
This is my current code:
HTML
<form action="#" method="get">
<div class="form-group" style="max-width: 300px; width: 98%;">
<select name="status" id="status" class="form-control" onchange="getProjectsByStatus(this.value)">
<option value="">Select a status</option>
<?php foreach ($status as $stat) { ?>
<option value="<?php echo $stat['status_id']; ?>"><?php echo $stat['status']; ?></option>
<?php } ?>
</select>
</div>
</form>
Javasscript
function getProjectByStatus(value) {
var current = document.getElementById('project-status').value;
if (value == "") {
document.getElementById('project-status').innerText = this.current;
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('project-status').innerHTML = this.responseText;
}
};
xmlhttp.open('GET', 'getProjectsByStatus.php?status='+value, true);
xmlhttp.send();
}
}

I would recommend, not to use html attributes like 'onchange'. Functions, used by those attributes must be in the global namespace.
This should be prevented. Instead, you should register the event from your javascript code. The following example uses jquery.
The code would be different, if you use vanilla js or another framework.
$(function() {
var $status = $('#status');
var previousValue = $status.val();
$status.change(function() {
var newValue = $status.val();
// here your logic
});
});
With such approach, you can store the initial state of the input and access it, if the value of the select field is changed. Additionally you prevent your app from writing into the global namespace.

Related

Get value of a column of a row where select option value changed

I am trying to model a webpage which allows users to give ratings to some projects and store these ratings in the background. I have a table like this
Project Id|Title|Rating. In rating column I have conditionally select tags in some columns otherwise there is some text. I added an onchange event on select which triggered a javascript function when value of option is changed, But i want to extract the value of project_id feild of the row where select value was changed. I am a newbie in javascript so I couldnt find anything which could solve my problem, I need that project id value because i need to store that value in my database which I have got it working via Ajax Calls.Here is my table below:
Code:
<?php if($row['status']==='complete' && $result2->num_rows==0 )
{ ?>
<select id="rating select" onchange="rating()" class="form-control" name="projectrating">
<option selected>0</option>
<option value="1" >1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<?php } ?>
<?php if($row['status']==='complete' && $result2->num_rows > 0 )
{ $row2=$result2->fetch_assoc();
$rating=$row2['rating'];
echo "You have already rated this Project!,You have given the project a rating of $rating";
} ?>
<?php
if($row['status']!=='complete') { ?>
<?php echo "Ratings only for complete projects" ?>
<?php } ?>
</td>
<?php } ?>
Javascript:( I need to fill variable parameter without value so I can send it using Ajax to a php script.)
<script>
function rating()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if(this.status===400){
alert("There was a problem while giving the rating");
}
if(this.status===200)
{
alert("Rating given succesfully");
window.location.reload(true);
}
}
};
xhttp.open("POST", "rating.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param=
xhttp.send(param);
}
To achieve expected result, use below option
Option1:
Using closest tr and children, you can get complete row values on change
Each cell can be obtained by "eq().text()"
Codepen -https://codepen.io/nagasai/pen/YVERRv
JS:
$(document).ready(function(){$('select').on('change',function(){
var $td= $(this).closest('tr').children('td');
var project= $td.eq(0).text();
console.log(project)
})
})
Option 2: Using plain javascript with parentElement and childNodes and using rating() onchange function
HTML:
<select onchange="rating(this)" class="form-control" name="projectrating">
JS:
function rating(a){
console.log((a.parentElement) .parentElement.childNodes[1].innerHTML)
}
a.parentElement will give the td enclosing select and parentElement of it is tr element and first child innerHTML gives the first column value
https://codepen.io/nagasai/pen/qmVQwp
first, you can't use multiple ID for one element
<select id="rating" onchange="rating()" class="form-control" name="projectrating">
then you should determine what you want to send
var paramToSend = document.getElementById("rating").value;
so your js will gonna be like this
function rating(){
var paramToSend = document.getElementById("rating").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if(this.status===400){
alert("There was a problem while giving the rating");
}
if(this.status===200){
alert("Rating given succesfully");
//window.location.reload(true);
}
}
};
xhttp.open("POST", "rating.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param="postedParam=" + paramToSend ;
xhttp.send(param); }
so in your rating.php you will get $_POST['postedParam']

Wordpress custom gallery settings - conditional display

Using print_media_templates i add some settings into wordpress gallery creator that allow me to chose gallery shortcode output (default gallery, masonry, slider) based on additional shortcode parameters.
My code so far :
<?php
add_action('print_media_templates', function(){ ?>
<script type="text/html" id="tmpl-custom-gallery-setting">
<label class="setting">
<span>Gallery Type</span>
<select name="type" data-setting="type" onchange="getval(this);">
<option value="default">Default</option>
<option value="masonry">Masonry</option>
<option value="slider">Slider</option>
</select>
</label>
<div id="slider-settings">
<label class="setting">
<span>Animation</span>
<select id="gallery-type" name="animation" data-settings="animation">
<option value=""></option>
<option value="fade">Fade</option>
<option value="slide">Slide</option>
</select>
</label>
</div>
</script>
<script>
jQuery(document).ready(function() {
wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
template: function(view){
return wp.media.template('gallery-settings')(view)
+ wp.media.template('custom-gallery-setting')(view);
}
});
});
</script>
<?php
});
?>
It's only small part as example since there's much more options to each gallery type. Since there's lot of options i want to display only one corresponding to selected gallery type. In this example i want to display #slider-settings only when #gallery-type select value == "slider".
As for checking select value i found this code:
<script>
function getval(sel) {
if (sel.value == "slider") {
alert(sel.value);
}
}
</script>
with return selected type value (along with onchange="" on #gallery-type select) and display it if it's set to "slider".
But when i want to hide #slider-settings like :
function getval(sel) {
if (sel.value != "slider") {
$('#slider-settings').hide();
}
}
it's not hiding at all.
You have to handle native update function. Update function is fired for each label when a single change is made. (media-views.js line 7232)
var oldUpdate = wp.media.view.Settings.Gallery.prototype.update;
wp.media.view.Settings.Gallery.prototype.update = function(key) {
if( key === "type" ) {
var value = this.model.get( key );
if ( value === "slider" ) {
setTimeout(function(){
jQuery("#slider-settings").css({"display":"block"});
});
} else {
setTimeout(function(){
jQuery("#slider-settings").css({"display":"none"});
});
}
}
// Initialize native code.
oldUpdate.apply(this, arguments);
};
Somehow i managed to get it work by hiding #slider-settings using not jQuery but javascript :
<script>
function getval(sel) {
if (sel.value != "slider") {
document.getElementById('slider-settings').style.display = 'none';
} else {
document.getElementById('slider-settings').style.display = 'block';
}
}
</script>
But to get value it's has to change (since it's onselect=) so first time i display settings it's not hiding. And as i searched there's seems to be not anything like onload= i can use with .
Or is there a way to just reselect it on load ?

How to call a function if checkbox checked and remove from appended list if unchecked

This is how the flow like:
I first derive the value of checkbox and pass the value to a function to trigger ajax. That ajax function return a list of data in multiple group in select box. Each time a checkbox checked, the value will be appended into the selectbox. But I want to remove the value from selectbox when checkbox unchecked.
Now, when I click on the checkbox the value is passed to the function no matter I check or uncheck. How to control here?
first script
<script>
$("input[type=checkbox]").change(function() {
var selectedval = ($(this).val());
var selectedtext =($(this).next().text());
sendtobox(selectedval);
});
</script>
second script (function)
<script>
var xmlhttp = false;
try
{
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
}
catch(E)
{
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}
function sendtobox(param)
{
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('show');
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
}
//document.getElementById("show").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+param,true);
xmlhttp.send();
}
</script>
HTML
<input type="checkbox" name="level" id="level" class="level" value="1"><label>Primary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="2"><label>Upper Secondary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="3"><label>University</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="4"><label>Lower Secondary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="5"><label>Pre University</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="6"><label>Skills/Languages</label><br/>
getuser.php
<?php
$q= intval($_GET['q']);
$con = mysqli_connect('localhost','root','','wordblend_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"test_db");
//$sql="SELECT * FROM tbl_subjects WHERE level_id = '".$q."'";
$sql="SELECT * FROM tbl_levels,tbl_subjects WHERE tbl_levels.level_id=tbl_subjects.level_id AND tbl_levels.level_id='$q'";
$result = mysqli_query($con,$sql);
?>
<?php
while($row = mysqli_fetch_array($result)) {
$levels=$row['level_name'];
$subjects= $row['subject_name'];
$subjects_id= $row['subject_id'];
?>
<optgroup label="<?php echo $levels;?>">
<option value="<?php echo $subjects_id;?>"><?php echo $subjects;?></option>
</optgroup>
<?php
}
?>
In onchange event, check for the checked status of the checkbox and then perform action accordingly.
$("input[type=checkbox]").change(function() {
if($(this).is(":checked")) {
var selectedval = $(this).val();
var selectedtext = $(this).next().text();
sendtobox(selectedval);
}
else {
// remove the items
}
});
Regarding removal of items, you must track which values are added for that particular checkbox. Only then you can remove those particular items.
EDIT based on comments
In your PHP code, add an identifier for the items added based on the checkbox. I'm adding the $q itself which is the checkbox value as class name.
<optgroup label="<?php echo $levels;?>" class="<?php echo $q;?>">
<option value="<?php echo $subjects_id;?>"><?php echo $subjects;?></option>
</optgroup>
Now in your jquery code:
$("input[type=checkbox]").change(function() {
var selectedval = $(this).val();
if($(this).is(":checked")) {
var selectedtext = $(this).next().text();
sendtobox(selectedval);
}
else {
$("optgroup."+selectedVal).remove();
}
});
Now this will remove the optgroups added by the ajax call.
Check the checked property of the checkbox.
$("input[type=checkbox]").change(function() {
var selectedval = ($(this).val());
var selectedtext =($(this).next().text());
if (this.checked) {
// do something else
} else {
sendtobox(selectedval);
}
});
Edit:
About removing, I assume you wish to undo on uncheck what you do here:
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML;
Instead of adding the response text directly, add it as a new dom element inside the show element with some unique identifier you can later use to remove it. Something like this (I use jquery since you seem to use that too in your first script, this is all doable without it of course):
var ajaxElm = $('#show');
ajaxElm.append($('<span id="uniqueidgoeshere">').append(this.responseText))
And then when you remove it refer to that id. The id should be deducible from the id (or other attributes) of the changed checkbox.

Javascript to hide selected option

I have this code to hide selected options:
function connect()
{
$(".selectbox option").show();
$(".selectbox").each(function(i) {
var obj = $(".selectbox option[value='" + $(this).val() + "']");
if($(this).val() != "") obj.hide();
});
}
function to()
{
$(".selectboxes option").show();
$(".selectboxes").each(function(i) {
var obj = $(".selectboxes option[value='" + $(this).val() + "']");
if($(this).val() != "") obj.hide();
});
}
but my problem now is that, I use PHP to generate the select tag, and in that php code i have a condition that once it sees this value it will automatically add selected=selected. but my JS would still display that variable in the drop down even though it is already selected. i tried adding:
$('.selectboxes option:selected').find("option").hide();
but it did not work. any idea on how should i solve this problem?
BTW: i forgot to mention that, the php code will generate multiple select tags with the same values that will use that function, thus when i have 3 select tags 1 will have the pre selected value and the other 2 will be null, now when i click on either 2 of those that have no values selected yet i can still see in the drop down the choice that was already pre selected in select 1, what i wanted to do is that it should be automatically hidden, with that function it will not hide it until i select other choices from the drop down. since this line:
$(".selectbox option").show();
would display all choices in the drop down, is there a condition for it to exempt "this" value?
SELECT PART:
for($z=0;$z<$rows_updatedrow;$z++)
{
?>
<select id = "sc" name = "connect_array[]" class="input-select selectbox" onchange = "connect()">
<option value = "">--Select--</option>
<?php
for($zz=0;$zz<$rows_getconnect;$zz++)
{
$data_getconnect = mysql_fetch_assoc($query_getconnect);
$field_name_getconnect[] = $data_getconnect['field_name'];
$field_display_getconnect[] = $data_getconnect['field_display'];
$field_type_getconnect[] = $data_getconnect['field_type'];
if((($field_name_getconnect[$zz] == "friends_name" && $connect == 2) || $field_type_getconnect[$zz] == "email") && $z == 0){
$selected = "selected=selected";
}else{
$selected = "";
}
?>
<option value = "<?php echo $field_name_getconnect[$zz]; ?>" <?php echo $selected; ?>><?php echo $field_display_getconnect[$zz]; ?></option>
<?php
}
?>
</select>
connect to
<br/>
<?php
}
?>
</div>
<div class = "right">
<?php
for($a=0;$a<$rows_updatedrow;$a++)
{
?>
<select name = "to_array[]" class="input-select selectboxes" onchange = "to()">
<option class = "option" value = "">--Select--</option>
<?php
for($aa=0;$aa<$rows_getto;$aa++)
{
$data_getto = mysql_fetch_assoc($query_getto);
$field_name_getto[] = $data_getto['field_name'];
$field_display_getto[] = $data_getto['field_display'];
$field_type_getto[] = $data_getto['field_type'];
if((($field_name_getto[$aa] == "friends_name" && $to == 2) || $field_type_getto[$aa] == "email") && $a == 0){
$selected = "selected=selected";
}else{
$selected = "";
}
?>
<option class = "option" value = "<?php echo $field_name_getto[$aa]; ?>" <?php echo $selected; ?>><?php echo $field_display_getto[$aa]; ?></option>
<?php
}
thank you
You already have the selected option in your selector - no need to find option - as that will return you an empty array
$('.selectboxes option:selected').hide();
// get rid of .find('option')
To exempt this value.. I'm guessing you're referring to the selected value.. you can use :not as undefined stated
$(".selectbox option:not(:selected)").show();
You can take out the inline onChange since you are using jQuery.. and bind the change event handler to the select elements on dom ready
$(function(){
$('select').change(function(){
var $sel = $('option:selected'); // get all selected options
$('option').show(); // show all options
$sel.each(function(i,v){ // loop through selected options
var $index = $(v).index(); // get index of selected option
$('select').not($(this).parent()).each(function(){ // loop through other select - not current one
if($index != 0){ // not default index
$(this).find('option').eq($index).hide(); // hide selected option in other dropdowns
}
});
});
}).change(); // <-- trigger change right away
});
http://jsfiddle.net/VE7jA/
$('.selectboxes option:selected').find("option").hide();
You are trying to find('option') inside option.. Try this
$('.selectboxes option:selected').hide();
You can also remove the element once and for all if you are using it again..
$('.selectboxes option:selected').remove();
To remove a option based on value you can try
$('.selectboxes option[value="0"]').remove() ; // Removes option with value 0
As it's been said, you're trying to find an option within an option, so you'll have to get rid of the .find call.
Apart from that, hiding <option> elements do not work cross-browser, so you'll have to remove the options instead, and add them back when necessary. There are several ways to manage that, all involving storing the full list of options in a variable (as an array, an object, or even HTML string).
Hiding option elements is not always supported. A more idiomatic approach would be to disable it.
obj.prop("disabled", true);
Or simplify it like this.
$(".selectbox option:selected").prop("disabled", true);
Or this.
$(".selectbox").each(function() {
this.options[this.selectedIndex].disabled = true;
});

how to run function to selection which is dynamically added

I am appending some HTML elements to the page dynamically. There can be multiple items added and can be added a different times...so it is hard to use a "bind".
I decided to use an inline function---but this does not work on Firefox...works on all other browsers. Notice the onClick for the options. Also, I have tried onblur, onchange, and on select. None of these work with Firefox.
My goal is to have these functions run when the option is selected. I guess I am just missing something.
$("#billTasks").find('tr')
.append('<td><fieldset><select>
<option class="fixedRate" onClick="fixedOption(this)" id="billFixedSelect" value="1">Fixed Rate</option>
<option class="hourly" onClick="hourlyOption(this)" id="billHourlySelect" value="2"></option>
</select>
<input type="text" placeholder="Rate" class="fieldWidth100 rate currency" style="margin-right:10px;"/>
<select class="schedule">
<?php while($row = $db->sql_fetchrow($result)){
echo "<option value=\'{$row['schedule']}\'>{$row['schedule']}</option>\\n";}?>
</select></fieldset></td>');
This is the code in question (in the append string)
<select>
<option class="fixedRate" onClick="fixedOption(this)" id="billFixedSelect" value="1">Fixed Rate</option>
<option class="hourly" onClick="hourlyOption(this)" id="billHourlySelect" value="2"></option></select>
Why Inline You try some thing like this.
$("#billTasks").find('select').live("change", function() {
var SelectedValue = $(this).val();
if (SelectedValue == '1') {
//your task
}
if (SelectedValue == '2') {
//Your Task
}
});
You can use delegate event handler for that:
$('#billTasks ').on('change', 'select', function() {
// your code
hourlyOption(this); // here this points to select itself
});
Read here
I would recommend using a class for this. What you could do is something like this:
function Option(html, events) {
var o = $(html);
for(var k in events) {
o.bind(k, events[k]);
}
return o;
}
Use this something like this:
var o = new Option('<option>blah</option>', { click: function() { } ... });
and o is just a new jquery object. So you can use it anyway.

Categories

Resources