Run JavaScript if key pressed != ENTER - javascript

Im working on a MVC4 site, and I have a webgrid with a search textbox. My Textbox is inside a form, which will be submitted when I press enter. I also have a onkeypress script bound to the textbox, that will, after 3 sek, update my webgrid with what else is entered.
My problem is, that I only want to run the script if not the last key pressed is Enter.
My code looks like this:
#using (Ajax.BeginForm("Filter", new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "projects" }))
{
<div class="paddingTextToleft">
Search:
<input id="searching" name="searchString" type="text" value="" onkeypress="return keypressed()">
<p class="error">#ViewBag.SearchMessage</p>
</div>
<br />
}
And the script:
var timeoutReference;
function keypressed() {
if (window.event.keyCode == 13) {
//Do not run the script!
return true;
}
else {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function () {
var value = $("#searching").val();
$.ajax({
url: '#Url.Action("Filter", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('#projects').html(result);
});
}, 3000);
}
};
I want it to stop the script (or not run the rest of it), if the key pressed is enter.
Hope anyone can help me.
Thanks

Firstly you are not sending Event to the function.
Call it with some parameters e.g:
<input id="searching" name="searchString" type="text" value="" onkeypress="keypressed(e)">
Then accept this event in a function:
var timeoutReference;
function keypressed(e) {
if (e.keyCode == 13) {
//Do not run the script!
return;
}
else {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function () {
var value = $("#searching").val();
$.ajax({
url: '#Url.Action("Filter", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('#projects').html(result);
});
}, 3000);
}
};

Related

problem with prevent and continue submit form after ajax execution

I have form with select. If select value is equal to 2 then part of form is sendign asynch via ajax and later the rest of the form should be sending via POST function. My problem is when I click submit ajax execution is performs correctly but POST method stuck, nothing happens. It looks like be page refresh.
My code
$('form').submit(function(e) {
if($('#car_type').val() == 2)
{
e.preventDefault();
e.returnValue = false;
var type = $('#new_type').val();
var number = $('#numer').val();
var form = $(this);
$.ajax({
url: "{{ url('cars/type') }}",
method: "POST",
context: form,
data: {type: type, number: number, _token: "{{ csrf_token() }}"},
success: function (result) {
if (result.result > 0) {
} else {
$("#msg").html("Errors, try again later!");
$("#msg").fadeOut(2000);
}
},
error: function (xhr) {
console.log(xhr.responseText);
},
complete: function() {
this.off('submit');
this.submit();
}
})
}
});

Validation DropDownList outside grid

I have kendo dropdownlist and button submit. I want if the user not select anything in dropdown(position), there will be validation that inform the user must select one position at least at dropdown. Then, if the user has click the position, so the user can submit the data. I have used some method like "required" but not working.
HTML
<input id="dropdown" style="width:200px;" />
JavaScript for kendoDropDownList (position)
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "./testjson.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: function(e){
console.log(this.value());
// $('#AccountingTree').data('kendoTreeView').homogeneous.read();
homogeneous1.read();
homogeneous2.read();
homogeneous3.read();
homogeneous4.read();
homogeneous5.read();
homogeneous6.read();
homogeneous7.read();
homogeneous8.read();
homogeneous9.read();
homogeneous10.read();
homogeneous11.read();
homogeneous12.read();
homogeneous13.read();
homogeneous14.read();
}
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
For dropdownlist above, i"m using homogeneous data (treeview).
Anyone have any idea or reference on this question?
JavaScript AJAX call for submit button
//AJAX call for button
$("#primaryTextButton").click(function(){
if($("#dropdown").data("kendoDropDownList").value() == ""){
kendo.alert("Please select position.");
}
});
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS")
{
kendo.alert("Data saved");
}else
{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
});
When you click the button, just get the value of the kendoDropDownList and do a
conditional statement. Hope this helps. Happy Coding ;D
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").data("kendoDropDownList").value();
if(test == ""){
kendo.alert("Please select position.");
}
else{
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS"){
kendo.alert("Data saved");
}
else{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
}
});

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

stopping a function after first click, to prevent more executions

I have this function
function display() {
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
and it serves its purpose, the only problem is, a user can click on for as many times as possible, and it will send just as many requests to new.php.
What I want is to restrict this to just 1 click and maybe till the next page refresh or cache clear.
Simple example would be :
<script>
var exec=true;
function display() {
if(exec){
alert("test");
exec=false;
}
}
</script>
<button onclick="javascript:display();">Click</button>
In your case it would be :
var exec=true;
function display() {
if(exec){
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
exec=false;
}
});
}
}
This should do what you want:
Set a global var, that stores if the function already was called/executed.
onceClicked=false;
function display() {
if(!onceClicked) {
onceClicked=true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
}
During onclick, set a boolean flag to true to indicate that user clicked the link before invoking the display() function. Inside the display() function, check the boolean flag and continue only if it is true. Reset the flag to false after the AJAX completed processing (successful or failed).
You can use Lock variable like below.
var lock = false;
function display() {
if (lock == true) {
return;
}
lock = true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function (data) {
$('.daily').html(data);
lock = false;
}
});
}
you can implement this with that way too
$(function() {
$('#link').one('click', function() {
alert('your execution one occured');
$(this).removeAttr('onclick');
$(this).removeAttr('href');
});
});
function display(){
alert('your execution two occured');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="display();" id='link'>Have you only one chance</a>

on click save data of drop down list using Java Script , Jquery or Ajax

I have a drop down list. I am trying to save data of that drop down list on click event without using a button. I have tried some code but it is not working please help.
Here is the view of my drop downlist
#model MyYello.Admin.Models.FeedBack
#{
ViewBag.Title = "Feed Back";
}
#*#using (Ajax.BeginForm("SelectFeedBack", "Admin", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "mainContent" }, new { #id = "formId" }))
*#
<form method="post" id="formId" action="#Url.Action("SelectFeedBack","Admin")">
#Html.ValidationSummary(true);
<fieldset>
#Html.HiddenFor(item => item.FeedBackId)
<legend>Create Notes</legend>
<div class="editor-label">
#Html.LabelFor(item => item.FeedBackDrpDown, "Select feed Back")
</div>
#Html.DropDownList("FeedBack")
<input type="hidden" id="isNewNote" name="isNewNote" value="false" />
#* <p>
<input type="Submit" value="Save" id="Save" />
</p>*#
#* #Url.Action("CreateNote", "Admin")*#
</fieldset>
</form>
<script type="text/javascript">
$(function () {
$("#FeedBack").change(function () {
console.log("test");
$("#formId").submit(function () {
console.log("test1");
$.ajax({
type: "POST",
//url: urlAction,
data: {},
datatype: "JSON",
contentType: "application/json; charset=utf-8",
success: function (returndata) {
if (returndata.ok)
window.location = returndata.newurl;
else
window.alert(returndata.message);
}
});
});
});
});
You can adjust your onChange-Method like this:
$("#FeedBack").change(function () {
var urlAction = "/whatever/url/"; // someURL
// var urlAction = $("#FormId").attr("action"); // or grab the form-url?
var postData = {
"whateverName" : $(this).val() // selected drop-down-value
};
$.ajax({
type: "POST",
url: urlAction,
data: postData, // send postData-Object
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function (returndata) {
// make shure that the attributes ok,newurl and message are available - otherwise this throws an error and your script breaks
if (typeof returndata.ok !== "undefined" && typeof returndata.newurl !== "undefined" && returndata.ok)
window.location.href = returndata.newurl;
else
window.alert(returndata.message);
}
});
});
this is how you just submit the select-field-value to whatever URL. Do you wish to submit the whole form when the dropdown changes?

Categories

Resources