I got multiple checkboxes and labels and when the answer is correct I want to change the background color of the selected checkbox and label
<input type="checkbox" id="a" class="check-with-label" />
<label for="a" class="question_box">
<?php echo $vraag[0]['A'] ?>
</label>
<input type="checkbox" id="b" class="check-with-label" />
<label for="b" class="question_box">
<?php echo $vraag[0]['B'] ?>
</label>
and when the user presses submit it calls an ajax call to a script to check if it is the correct answer or not.
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
this.css('background-color', 'green');
//selected_box.css('background-color', 'green');
} else {
this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
problem is I don't know how to call the correct box because when the user presses submit the this variable is now the submit button and not the checked box (There can only be one checkbox selected at the time_.
So the question is how do I replace the background color of the selected AND the correct box from
.check-with-label:checked + .question_box {
background-color: orange;
}
to
background-color:green
(and for incorrect red)
Try changing the label instead of this
You've already got the ID of the label
(var selected = $(this).attr('id');)
Which will probably return a/b/c/d and then use
$('label[for="'+selected+'"]').css('background-color', 'green'); //or red in the else statement
this styles the label for the selected id, in this case d
the code above basicly means:
$('label][for="d"].css('background-color','green'); //or red
but then using the chosen variable
Goodluck!
In success use selected_obj.css instead of this.selected and pass $(this) to selected_obj
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
var selected_obj = $(this);
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
selected_obj.css('background-color', 'green');
//selected_box.css('background-color', 'green');
} else {
selected_obj.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
Try this
$('#bottom').on('click', function(){
$('#antwoorden .check-with-label').each(function() {
var selected = $(this).attr('id');
var isChecked = $(this).is(':checked'));
if (!isChecked) {
return;
}
var selected_obj = $(this);
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
selected_obj.css('background-color', 'green');
} else {
selected_obj.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
After the page is rendered and displayed to user, PHP will no longer run. Therefore, in your $('#bottom').on('click' function, the PHP code won't work. The trick is to store that information when building the page, such as by writing it into a data attribute or some such.
Inside the AJAX success function the $(this) object is not available. Set it to a global variable and you will be able to access the value.
/* javascript/jQuery */
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = this.id; //faster, same result
$this = $(this);
selected = selected.toUpperCase();
var data = {
//change next line - PHP finished running
vraag_nummer : $this.attr('data-vn'),
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
$this.css('background-color', 'green');
} else {
$this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
<!-- HTML: -->
<input id="vraag_nummer" data-vn="<?php echo $vraag[0]['id'] ?>" type="text" />
Related
I have a select box, that contains option X and O. I put a function Onchange on it to populate the value in the textbox.
<input type="text" id="remarks1"/>
this is my script for select box to populate value in textbox :
$(document).on('click', '#1', function() { ////---make td transform to dropdown list box when click---///
if($(this).find('select').length == 0) {
$(this).empty(); //clears out current text in the table
$(this).append('<select onchange="myFunction()" id="Remarks" name="Remarks"><option value=""></option><option <?php if ($Remarks=='X') echo 'selected';?> value="X" style="font-size:20px;font-weight:bold;">X<option style="font-size:20px;color:green;font-weight:bold;" <?php if ($Remarks=='O') echo 'selected';?> value="O">O</select>');
}
});
function myFunction(){
var dropdown1= document.getElementById("Remarks"); ////===== select box
var selection1 = dropdown1.value;
//console.log(selection1);
var emailTextBox1 = document.getElementById("remarks1"); //==== textbox
emailTextBox1.value = selection1;
}
then this is my ajax when button save is click :
$(document).on('click','#btnSave',function(){
var employeeName = document.getElementById('employeeName').value;
var r1 = document.getElementById('remarks1').value;
var r2 = document.getElementById('remarks2').value;
$.ajax({
type: 'post',
url: 'update_data.php',
data: {
'DAY1' :r1,
'DAY1_A' :r2,
'employeeName' :employeeName
},
success: function(data){
$("#content").html(data)
$(".loader").fadeOut("very slow");
$("#content").hide().fadeIn(500)
alert("Changes Succesfully Saved!");
},
error:function(data){
alert('Failed');
}
})
});
how can I retain now the value of textbox after ajax success?
You can use localStorage to store the value so that you use that later:
function myFunction(){
var dropdown1= document.getElementById("Remarks"); ////===== select box
var selection1 = dropdown1.value;
localStorage.setItem('remarks', selection1); // set the value in localStorage
var emailTextBox1 = document.getElementById("remarks1"); //==== textbox
emailTextBox1.value = selection1;
}
Then in the AJAX success:
success: function(data){
$("#content").html(data)
$(".loader").fadeOut("very slow");
$("#content").hide().fadeIn(500)
var remarks = localStorage.getItem('remarks'); // get from localStorage
document.getElementById("remarks1").value = remarks; // set the value in the text box;
alert("Changes Succesfully Saved!");
}
I am getting value in Column , following is the code.
grid.Column(columnName: "Name", header: "Name",format: #<text>
<span id="Name">#item.Name</span></text>, canSort: false),
want to use this value in function which I have called on delete button
function DeleteEnterpriseID() {
var checkID = $(".edit-mode:checked").map(function () {
return this.value;
}).toArray();
alert(checkID.join(","));
if (confirm("Are you sure you want to delete?") == true) {
var url = "#Url.Action("DeleteEnterpriseIdDetails")";
var pname = $('#Name').val(); //// Here I want that value from the clicked row so that I can pass that to controller.
alert(pname);
$.ajaxSetup({ cache: false });
$.post(url, { Pname: pname, EnterpriseID: checkID.join(",") })
.success(function (response) {
if (response != null && response.success) {
alert(response.responseText);
window.location.href = response.newurl;
} else {
alert(response.responseText);
}
})
.error(function (response) { alert("error"); });
}
else {
return false;
}
}
But I am getting blank value for Name from clicked row.
Kindly assist.
It should be:
var pname = $('#Name').text();
Because its a span tag and not an input element. val() works for input elements.
How to delete a record from database through AJAX using php and also when link is clicked it returns to same page and new list is updated when a link is clicked and id passes through this link ? I am new to AJAX and php
<a class="delete_data" id="<?php echo $row['id']; ?>">Delete</a>
ajax
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // Sucess
} else { // Error }
}
});
});
});
delete.php
$id = $_POST['delete_id'];
$query = "delete from TABLE NAME where ID = $id";
#TOORPIZZZ You can add this to remove the row from the display without refreshing
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
var parent = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { parent.slideUp(300,function() {
parent.remove();
} else { // Error }
}
});
});
});
Make sure you don't have } in a comment by //Error. It took a while until I discovered this.
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
var parent = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { parent.slideUp(300,function() {
parent.remove();
} else { // Error } <----------------
}
});
});
});
I'm having a problem not being able to have a default selected option when i fill the select box with ajax call, i have the value, but not a default one, I want that the default one will be the first value i get from the call;
my HTML is (we will work on select2):
<div class="containerdiv">
<select class="select1" name="dettaglio1">
</select> <select class="select2" name="dettaglio2">
</select> <select class="select3" name="dettaglio3">
</select>
</div>
while the ajax call is that (Comments are for you):
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
and my html after the call is(F12) :
<div id="select-4-button" class="ui-btn ui-icon-carat-d ui-btn-icon-right ui-corner-all ui-shadow">
<span class="select2"> </span>
<select class="select2" name="dettaglio2">
<option value="0">option1</option>
<option value="1">option2</option>
<option value="2">option3</option>
<option value="3">option4</option
><option value="4">option5</option>
</select></div>
Is the problem on span element? and why it's blank ?
Select the default value once all the options are loaded. Check below
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$('select[name=dettaglio2]').val($('select[name=dettaglio2] option:first').val());
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
$(".select2")[0].selectedIndex = 0;
You should try this when your select tag is already populated/.
Thank to Pugazh I modified his answer and came to this working solution:
$("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
the full code:
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
I answered because is more clear the solution, but thumbs up his answer and comments that helped me.
(I've thumbed up everyone that helped, thanks a lot) ;)
Use following once your options loaded :
$('.select2 option:eq(1)').prop('selected', true)
Here 1 is index.you can set default value by index easily.
Change your success part to below code:
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$('.select2 option:eq(1)').prop('selected', true)
},
If there is 2 .select2 class then use index for .select2
( Check This Link for same)
I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>