Retain value in textbox after ajax success - javascript

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!");
}

Related

Can't get Hidden Input Field (Dynamic) Value in other pages with Jquery

I have a hidden input field in page "A". Whom value I am populating dynamically as there are 100+ values. The value changes when different element is clicked.
I want the set value in a different page "B". I am using the simple method of getting value by id but the output cames undefined.
Here is some code:
Input Field: <input type="hidden" id="sel_s_n" value="" name="sel_s_n">
Populating on element click:
jQuery('.shades-popup').click(function () {
jQuery('#myModaldcm .modal-body').css('display', 'none');
title = $(this).data('dcmtitle');
$("#sel_s_n").val(title);
var rgb = $(this).data('dcmrgb');
var img = $(this).data('dcmimg');
var pro_tit = $(this).data('dcmpt');
var pro_id = $(this).data('pid');
jQuery('.dcmptitle').html(title);
jQuery('.csdcmp').css('background', 'rgb(' + rgb + ')');
jQuery('.cdmpi').attr('src', img);
jQuery.ajax({
type: "post",
dataType: "json",
url: dcmAjax.dcmajaxurl,
data: { action: "get_dcm_products", post_id: pro_id },
success: function (response) {
if (response.type == "success") {
jQuery("#dcmselextt").html(response.data);
jQuery('#myModaldcm .modal-body').css('display', 'block');
}
else {
alert("Network Error! Try Again")
}
console.log(response);
}
})
});
$("#sel_s_n").val(title); --> This line add the value.
On the second page "B" I am getting it like alert( $("#sel_s_n").val() );
Can somebody point out what I am doing wrong.
Thanks

input field not changes on change of dropdown if i insert input field value on form

Input field value change on change of drop down but if i change input field value in form then on change of drop down input field value doesnt change .. this is jquery..
$('#Add-DSR-Form').on( 'change', 'tbody td select.cylinder_id', function () {
var $row = $(this).parents("tr"),
index = $row.attr('data-item-index');
var CylinderID = $(this).val();
if(CylinderID < 1)
{
$row.find('[id="Rate[]"]').attr('value', "").end();
grandTotal();
return false;
}
else
{
var Action = 'GetCylinderDetail';
var dataString = 'Action='+ Action +'&CylinderID='+ CylinderID;
$.ajax({
type: "POST",
url: "includes/loader_functions.php",
data: dataString,
cache: false,
success: function(result)
{
//alert(result);
//alert(JSON.parse(result));
var obj = JSON.parse(result);
$row.find('[id="Rate[]"]').attr('value', obj.CylinderPrice).end();
grandTotal();
return true;
}
});
}
});

Change checkbox + label jquery

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" />

I need to change my success when my checkbox get unchecked

Here is my code:
$(document).ready(function() {
$( ".iCheck-helper" ).on( "click", function(){
var sel = $('.i-check:checked').map(function(_, el) {
// if($(this).is(":checked")){
return $(el).val();
}
}).get();
// alert(sel);
var nme = $('.i-check:checked').map(function() {
// return $(el).val();
return $(this).attr("name");
}).get();
// alert(nme);
var value = this.value;
// this(attir)
var city_name =<?php echo json_encode($cityname) ?>;
var start =<?php echo json_encode($start)?>;
var end =<?php echo json_encode($end)?>;
var room_count =<?php echo json_encode($room_count)?>;
var member_count =<?php echo json_encode($member_count)?>;
var selt_guest =<?php echo json_encode($selt_guest)?>;
var selt_room =<?php echo json_encode($selt_room)?>;
// alert(city_name);
$.ajax({
// alert();
type: "POST",
url: "hotelresults",
data: {
key : sel,
name:nme,
search_city:city_name,
start:start,
end:end,
selt_guest:selt_guest,
selt_room:selt_room,
room_nf:room_count,
guest_nf:member_count,
},
success: function (data) {
$('.hotel_list').html(data);
}
});
});
});
While clicking a checkbox this success function calls.And here sel & name are passed into the controller as in array manner.
If one of my checkbox is unchecked it should pass the remaining values of the array in both sel and name.
And if all the checkboxes are unchecked my sel & name value set to null.
So here,when my values get null or all checkboxes are set unchecked I need to pass another set of data in my Success like as follows.
data: {
search_city:city_name,
start:start,
end:end,
selt_guest:selt_guest,
selt_room:selt_room,
room_nf:room_count,
guest_nf:member_count,
}
And here, I need that .map function as must because without that function my values didn't pass to the controller.
Here, rather than creating object directly in the Ajax call. Intiaite it first in a variable and assign that variable to data in call. Example below:
Var dataToSend = { search_city:city_name, start:start, end:end, selt_guest:selt_guest, selt_room:selt_room, room_nf:room_count, guest_nf:member_count}
Above are the properties which you need in every case.
Now check for optional ones as below:
If(nme && nme.length) {
dataToSend.nme = nme;
}
And same for other variable.
In last. In the Ajax call, assign variable to data, like below:
data: dataToSend
Thanks,
Manish kumar

On change event inside hidden input field

I have two AJAX functions. First function takes the result of the first input field and concatenates a string and then changes the value of the second input field. The second input field is (type=”hidden”). Second function checks if there was a change triggered in the second input field and then display the value on the third input field. Nothing is being triggered by the change of value made in input field # 2. Example
<script>
$(document).ready(function () {
var timer = null;
var $result=$("#result");
$result.data('url',$result.val());
function submitForm( input ) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
var url=$result.data('url'),
newUrl= url+input+'/';
$result.val(newUrl);
}
});
return false
}
$("#input").on("keyup", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 40);
})
});
$(document).ready(function () {
var timer = null;
var $result=$("#result").val();
function submitForm( input ) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
$result.val();
}
});
return false
}
$("#result").on("change", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 40);
})
});
</script>
</head>
<body>
<h1>Enter a word:</h1>
<form action="index.php" method="post">
Input: <input type="text" id="input" name="input"></br>
Concatenated Result1(hidden): <input type="hidden" style="width:200px;" id="result" name="result" value="http//www.example.com/"></br>
Concatenated Result2: <input type="text" id="result2" name="result2" value=""></br>
</form>
This answer is really a revamp of your code, but maybe it will do what you need and simplify things.
If you simply throw out the second input box, and show #result (make it not hidden), i think this code might work to get what you need accomplished, and simplify things a bit.
What this should do is submit a request to the server no more frequently than every 40ms and on success of that request, we update the display value of #result.
I'm now noticing that if this does actually solve the issue, then you've gotten away from the onChange issue completely, because the real trigger now is the keyup event.
$(document).ready(function() {
/** get the inputs we might need */
var $result = $('#result');
var $input = $('#input');
$result.data('url', $result.val());
var timer;
/** function to submit data to the server and
update the result input on success */
function submitForm( input, newValue) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
$result.val(newValue);
}
});
};
/** on key up, fill #result with the url + input */
$input.bind('keyup', function() {
var $this = $(this);
var inp = $this.val();
var url = $result.data('url');
var newValue = url + inp + '/';
if(timer) { clearTimeout(timer); }
timer = setTimeout(function(){
submitForm(inp, newValue) ;
}, 40);
return false;
});
});
The OnChange event is not fired when the contents of the field is changed programmatically. The OnChange event is only raised when a user enters data into the field.
That's just the way this works.

Categories

Resources