How to disable other input when this input OnKeyUp? - javascript

How to disable other input when this input OnKeyUp ?
When i input data into input name="inputid1" , i want to disabled other input
when i input data into input name="inputid2" , i want to disabled other input
when i input data into input name="inputid3" , i want to disabled other input
when i input data into input name="inputid4" , i want to disabled other input
How can i do this with javascript loop ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form-id" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
<input type="text" id="inputid1" name="inputid1" onKeyUp="fn_test1()">
<br>
<input type="text" id="inputid2" name="inputid1" onKeyUp="fn_test2()">
<br>
<input type="text" id="inputid3" name="inputid1" onKeyUp="fn_test3()">
<br>
<input type="text" id="inputid4" name="inputid1" onKeyUp="fn_test4()">
<br>
<span id="myplace"></span>
</form>
<?PHP
for($i=1;$i<=4;$i++)
{
?>
<script>
function fn_test<?PHP echo $i; ?>() {
$("#inputid2").prop('disabled', true);
$("#inputid3").prop('disabled', true);
$("#inputid4").prop('disabled', true);
setTimeout(function(){
$.ajax
(
{
url: 'test_mm16.php',
type: 'POST',
data: $('#form-id').serialize(),
cache: false,
success: function (data) {
$("#inputid2").prop('disabled', false);
$("#inputid3").prop('disabled', false);
$("#inputid4").prop('disabled', false);
$('#myplace').show();
$('#myplace').html(data);
}
}
)
}, 2000);
}
</script>
<?PHP
}
?>

This will work
$('#form-id input').on('keyup',function() {
$('#form-id input').attr('disabled','disabled'); //disable all
$(this).removeAttr('disabled'); //enable the one that triggers the event
doPost();
});
function doPost() {
$.ajax({
url: 'test_mm16.php',
type: 'POST',
data: $('#form-id').serialize(),
cache: false,
success: function (data) {
$('#myplace').show();
$('#myplace').html(data);
},
always: function() {
$('#form-id input').removeAttr('disabled');
}
}
)
}
Working example:
http://jsfiddle.net/z4apqjan/
Edited: I put the doPost function to execute the Ajax request.

There are to much messy things in your code, but I've made some corrections for you:
You have same names for four input elements, so you will always get inputid1 param in your PHP and I think this is not want you want to achieve.
You don't need to bind keyup for each element manually in html, better use advantage of jQuery, for this purpose I've added class attribute to all four inputs with value strangeInputs, you can change it respectively as you wish.
No need to create functions for each input, you already have enough information which separates the meaning of them.
Also after once keyup occurs to one of the input elements I think you no longer need keyup handler, so we will remove it after first it's been fired with jQuery's .off function. Edit: but because you send request all the time keyup occurs to the input we should not disable event listener
Finally your simplified code would look like this:
HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form-id" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
<input type="text" id="inputid1" class='strangeInputs' name="inputid1">
<br>
<input type="text" id="inputid2" class='strangeInputs' name="inputid2">
<br>
<input type="text" id="inputid3" class='strangeInputs' name="inputid3">
<br>
<input type="text" id="inputid4" class='strangeInputs' name="inputid4">
<br>
<span id="myplace"></span>
</form>
JavaScript:
/**
* scenario is simple, bind keyup event, when it fires once,
* execute desired code and remove keyup listener finally
*/
$(function(){
$('.strangeInputs').keyup(function(){
$('.strangeInputs').not(this).prop('disabled', true);
fn_test_inputs();
// $('.strangeInputs').off('keyup');
// in the case you send request at once keyup event occurs,
// you should not remove listener
});
});
function fn_test_inputs()
{
setTimeout(function(){
$.ajax
(
{
url: 'test_mm16.php',
type: 'POST',
data: $('#form-id').serialize(),
cache: false,
success: function (data) {
// here enable inputs again
$('.strangeInputs').prop('disabled', false);
$('#myplace').show();
$('#myplace').html(data);
}
}
)
}, 2000);
}
Simple input thing you can see here: http://jsfiddle.net/gttv53fg/

Related

How to send AJAX value as 1 when checkbox is checked and 0 when it is not checked?

I have a checkbox it's change text when checked (check is text = on, uncheck is text = off and this value are 0 and 1) I want get value 0 or 1 (check get 1 uncheck get 0) by ajax but I confuse in my code
$("#onoff").click(function() {
if ($(this).is(':checked')) {
$("#hidden_onoff").text("ON");
} else {
$("#hidden_onoff").text("OFF");
}
});
$('#onoff').change(function() {
if ($(this).prop('checked')) {
$('#hidden_onoff').val('1');
} else {
$('#hidden_onoff').val('0');
}
});
$.ajax({
url: "/on_off",
method: "POST",
data: {
onoff: $("#hidden_onoff").val(),
},
success: function(data) {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="on_off">
<div class="container">
<div class="form-check form-check-inline">
<input id="onoff" type="checkbox" checked="checked" />
<label class="checkbox-inline" id="hidden_onoff">ON</label>
</div>
</div>
</form>
You're setting the value of <label id="hidden_onoff"> rather than <input id="onoff">:
$('#hidden_onoff').val('1');
However, since you're using AJAX, it doesn't seem that you need to change the input's value anyway. You can define a variable based on whether the input is checked, and send that variable's value to the server.
Also, it doesn't seem that you need both click and change handlers. You can use the change event alone. If your intent is to change the input when its text is clicked, I suggest wrapping both the input and text elements in a <label>.
... you can nest the <input> directly inside the <label>, in which case the for and id attributes are not needed because the association is implicit (label # MDN)
Finally, it looks like you're executing the AJAX upon page load rather than upon input change. I recommend executing the AJAX from inside your event handler.
Here's a demonstration:
// select the input and label elements and store them as constants
const $onoff = $('#onoff');
const $label = $('#onoff_label');
// bind a change event handler to the input
$onoff.on('change', function() {
// define value and label (1 and ON, or 0 and OFF)
let cbox_value = $onoff.is(':checked') ? 1 : 0;
let cbox_label = cbox_value ? 'ON' : 'OFF';
// set label text (ON or OFF)
$label.text(cbox_label);
// send value via AJAX (0 or 1)
$.ajax({
url: "https://reqres.in/api/users",
method: "POST",
data: {
onoff: cbox_value
},
success: function(data) {
// show the result from server
console.log(data.onoff);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input id="onoff" type="checkbox" checked="checked">
<span id="onoff_label">ON</span>
</label>
1st: ID must be unique don't use same id for more than one element
2nd: $("#hidden_onoff") is a label so it has a .text() not .val()
3rd: You can use one element event to trigger another element event it will be easier to work with
Take a look at this sample code .. Changing ids to form_onoff and text_onoff
$(document).ready(function(){
$("#text_onoff").on( 'click' ,function() {
$('#onoff').prop('checked' , $('#onoff').prop('checked') ? false : true).change();
});
$('#onoff').on('change', function(){
$(this).val(this.checked ? '1' : '0');
$("#text_onoff").text(this.checked ? 'ON' : 'OFF');
console.log($('#onoff').val());
/*$.ajax({
url:"/onoff",
method:"POST",
data:{ onoff:$("#onoff").val()},
success:function(data){
console.log(data)
}
});*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form_onoff" >
<div class="container">
<div class="form-check form-check-inline" >
<input id="onoff" type="checkbox" checked="checked" value="1"/>
<label class="checkbox-inline" id="text_onoff">
ON
</label>
</div>
</div>
</form>
<script>
</script>
you need to do a loop for all the input of type check
$('input[type="check"]').each(function(){
$(this).val(($(this).prop('checked'))?1:0);
});

Prevent redirecting after post

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.
The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.
You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example
In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.
Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

Ajax disable the form fields

I use the following Ajax script to post data and to disable the send-button and the form fields. At the moment only the submit button disables on click, but I want all the fields to be disabled.
So that's why I added: var compl_form = $('form#updateBeschikbaarheid'); and compl_form.attr("disabled", "disabled");
But that won't work.
<script type="text/javascript">
$(document).ready(function(){
$("form#updateBeschikbaarheid").submit(function(event) {
event.preventDefault();
var formData = $(":input,:hidden").serialize();
var btnSubmit = $('#uploadenFormSend');
var compl_form = $('form#updateBeschikbaarheid');
$.ajax({
type: "POST",
url: "beschikbaarheid.insert.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
btnSubmit.val("Wacht op goedkeuring"); // put your normal text
btnSubmit.attr("disabled", "disabled");
compl_form.attr("disabled", "disabled");
}
});
});
});
</script>
Form:
<form method="post" id="updateBeschikbaarheid" name="updateBeschikbaarheid">
<input type="time" name="zaterdag_van" id="zaterdag_van" value="">
<input type="time" name="zaterdag_tot" id="zaterdag_tot" value="">
<input type="submit" class="button-pink" value="<?php echo $button_text; ?>" id="uploadenFormSend" name="uploadenFormSend">
</form>
You cannot disable a form like that, but you can disable the inputs:
$(':input').prop('disabled', true);
Or in older versions of jQuery
$(':input').attr('disabled', 'disabled');
.prop()
.attr()
EDIT: based on your question in the comments, you can leave a select box enabled like this:
$(':input').not('select').attr('disabled', 'disabled');
compl_form.prop("disabled", true);
try this.

JavaScript jQuery issue with submit button

I have a problem. I think it's because of the rendering but I don't know because that topic is new to me.
Okay, I have a simple form:
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Now i want to catch that submit using jQuery like:
$('[type=submit]').submit(function(e) {
e.preventDefault();
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
});
okay, that code works really good. It does what it should do. But, If I want to send a second request, the submit button doesn't work anylonger as intended. It tries to send the form using the default-action although I prevnted that - at least that's what I thought.
I did use google but I don't even know how to explain my problem.
Hopefully someone can help me, thanks a lot!
Greetz
Instead of .html() you can use:
.clone(true): Create a deep copy of the set of matched elements.
.replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
The event must be click if attached to submit button or submit if attached to the form.
The snippet:
$('[type=submit]').on('click', function (e) {
e.preventDefault();
var formHtml = $(this).closest('form').clone(true);
$.ajax({
dataType: "json",
url: 'https://api.github.com/repos/octocat/Hello-World',
beforeSend: function (xhr) {
$('form').html("sending mail");
},
success: function (data) {
console.log('Success');
$('form').replaceWith(formHtml); // I think here's the problem...
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Use $(document).on("click", "[type=submit]", function (e) { for dynamically created ekements instead of $('[type=submit]').submit(function(e) {
Use <input type="button"> instead of <input type="submit"> and add an onclick function like this:
<input type="button" onclick="_submitForm()" value="send that fancy mail">
And then your js will be:
function _submitForm(){
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
}
I hope that solved your problem.

PHP-AJAX passing input text to action url directly with ajax

Html:
<form id="yourFormId" method="POST" action="/">
{{csrf_field()}}
<div id="check" class="input-group margin-bottom-sm">
<input class="form-control" type="text" name="find" placeholder="Search">
<button type="submit"><div id="search" class="input-group-addon"><i class="fa fa-search"></i></div></button>
</div>
</form>
JS:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + this.val() );
});
});
</script>
That script doesn't work. I need an ajax solution to pass dynamically my input text to action url. How to do that?
Try this:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + $(this).val() );
});
});
</script>
i think u want to submit your form with ajax request with dynamic text field value.
you can use simple java script function on change or click event whatever you want or with ajax request
you simple use like this
window.location.href="/"+$(this).val();
return false;
This code will submit your form on keyup (as soon as you stop typing)
var timerid;
jQuery("#yourFormId").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
In this code you intercept the form submit and change it with an ajax submit
$('.form-control').bind('keyup', function() {
$("#yourFormId").submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: '/url/toSubmit/to',
data: $("#yourFormId").serialize(),,
success: function (response) {
//write here any code needed for handling success }
});
});
});
To use the delay function you should use jQuery 1.4. The parameter passed to delay is in milliseconds.

Categories

Resources