Submit can't see return false; - javascript

I know that I must add return false; to function called in onsubmit (I added it to function and onsubmit="" in HTML). But it doesn't work... Page freshing after pressing Enter or clicking submit button.
JavaScript generated forms:
AnswersHTML += "<div><form onsubmit='cheking(this," + a + "," + b + ", this); return false;'><input class='put' type='text' size='40'><input type='submit' value='Проверить'></form>
and function
function checking(answer, nums, numq, what) {
var usr = answer;
if (isNaN(answer)) {
usr = answer.value;
if (answer.value.length == "") {
usr = "Вы ничего не ввели!"
}
else {
answer = answer.value.toLowerCase();
}
}
if (answer == correct[nums][numq]) {
$(what).parent().parent().append("<br><span class='right'>Ответ: " + usr + "<br>Правильно!</span>").slideDown();
$(what).parent().parent().find(".put").remove();
$("#board").animate({ backgroundColor: '#2ecc71'});
$("#board").animate({ backgroundColor: '#f1c40f'}, 1000);
if (isPhysics[nums][numq]) {
physics++;
$("#presult").text(physics);
}
else {
life++;
$("#lresult").text(life);
}
}
else {
$("#board").animate({ backgroundColor: '#e74c3c'});
$("#board").animate({ backgroundColor: '#f1c40f'}, 1000);
var desciptionToWrong = "<br>" + description[nums][numq];
if (description[nums][numq] == false) {
desciptionToWrong = ""
}
$(what).parent().parent().append("<br><span class='wrong'>Ответ: " + usr + "<br>Неправильно!" + desciptionToWrong + "</span>")
$(what).parent().parent().find(".put").remove();
$(what).remove(".pressenter");
}
return false;
}
Sorry for my possibly disgusting code
Here's the full page https://rawgithub.com/ruslankh/Kurchatovy/master/index.html
Problem in function because when I'm replaced function to just alert, it was fine

Its probably due to type. You have wrong spelling in function call that would cause an error and call goes to server.
Change
'cheking(this," + a + "," + b + ", this);
To
'checking(this," + a + "," + b + ", this);

Your inline onclick has a typo, you left one of the c's out of the function name. This error likely terminates the click handler before it gets as far as the return statement.

Try this,
AnswersHTML += "<div><form data-a='"+a+"' data-b='"+b+"' class='myform'><input class='put... "
SCRIPT
$(function(){
$(document).on('submit','form.myform',function(){
checking(this, $(this).data('a'), $(this).data('b'), this);
return false;
});
});

Related

Vanilla JS addEventListener change on select fires only once

I am using an ecommerce system where I dont have access to HTML code or anything but I can add custom JS code to alter some things and CSS.
I need to edit the shipping info text which is right to Doba dodania text.
My issue is that the event fires only once and not on every select change event.
Can someone help me why it is firing only once? It was needed to add SetTimeOut too.
Please check the page and console logs here:
https://www.privlacuj.sk/Hacik-Offset-Light-Class-AT-21-cena-za-1ks-d2336_1013278452.htm
My code is:
<script type="text/javascript">
function change_doba_dodania() {
var c757_counter = document.querySelectorAll(".c757").length;
var variant = document.querySelectorAll(".c755.variant").length;
var out_of_stock = document.querySelectorAll(".c757.out-of-stock").length;
console.log(c757_counter);
console.log(variant);
console.log(out_of_stock);
if (out_of_stock > 0) {
console.log("Nincs raktaron");
}
if ( ( c757_counter >= 2 ) && ( out_of_stock == 0 ) ){
var dd_text = document.getElementsByClassName("c757")[1].innerHTML;
console.log(dd_text);
var dd_text_array = dd_text.split(" ");
var dd_final = dd_text_array.filter(String);
console.log(dd_final);
if (dd_final[2] == "zajtra") {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " " + dd_final[9] + " " + dd_final[10] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
} else {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " - " + dd_final[9] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
}
}
}
window.addEventListener('DOMContentLoaded', (event) => {
change_doba_dodania();
});
var variant = document.querySelectorAll(".c755.variant").length;
if (variant > 0){
document.querySelector('.c757 select').addEventListener('change', function()
{setTimeout(change_doba_dodania, 1500)});
document.querySelector('.c757 select').addEventListener('change',() =>
setTimeout(console.log, 1000, "Changed")
)
}
If i got your question, your problem is querySelector.
querySelector only selects the first element with the given class name. If you want to select all the elements with the given class name, you should use querySelectorAll.
document.querySelectorAll(".c757 select").forEach(select => {
select.addEventListener(...)
})

I Want to call multiple javascript function from codebehind on button click. it works fine for 3 javascript function but not more than that

I have a requirement to call 4 java script function from codebehind page of asp.net page it works fine for 3 javascript function but if i add 4th which is a validation function. The validation function works but not the other 3.
This works!
btnSubmit.OnClientClick = "return Getprodsize('" + hdnprdsize.ClientID + "');return formatSpecifications('" + hdnSpecifications.ClientID + "');return Getselectedvalue('" + hdndrop.ClientID + "')";
This doesnt work...
btnSubmit.OnClientClick = "return Validate();Getprodsize('" + hdnprdsize.ClientID + "');return formatSpecifications('" + hdnSpecifications.ClientID + "');return Getselectedvalue('" + hdndrop.ClientID + "')";
function Validate() {
var existing = $("#ctl00_contentMain_lblProductleft").text();
if ($('#ctl00_contentMain_txtProductName').val() == '') {
$('#ctl00_contentMain_txtProductName').focus().css("border-color", "red");
return false;
}
if ($('#ctl00_contentMain_Txtbrandname').val() == '') {
$('#ctl00_contentMain_Txtbrandname').focus().css("border-color", "red");
return false;
}
if ($('#ctl00_contentMain_Txtstock').val() == '') {
$('#ctl00_contentMain_Txtstock').focus().css("border-color", "red");
return false;
}
if ($('#ctl00_contentMain_Txtprice').val() == '') {
$('#ctl00_contentMain_Txtprice').focus().css("border-color", "red");
return false;
}
if ($('#ctl00_contentMain_txtShortDescription').val() == '') {
$('#ctl00_contentMain_txtShortDescription').focus().css("border-color", "red");
return false;
}
if ($('#ctl00_contentMain_txtLongDescription').val() == '') {
$('#ctl00_contentMain_txtLongDescription').focus().css("border-color", "red");
return false;
}
if ($('#ctl00_contentMain_ddlbcatgory option:selected').val() == 0) {
alert("Please Select Catagory");
return false;
}
if ($('#ctl00_contentMain_txtdeleverycharge').val() == 0) {
$('#ctl00_contentMain_txtdeleverycharge').focus().css("border-color", "red");
return false;
}
var txval = $('input[name=optradio]:checked').val();
$('#<%=hdnTax.ClientID%>').val(txval);
return true;
}
You can't have multiple return statements in the onClientClick attribute. The first one will return, and the rest will not be executed. You should call the other functions without using return, and then return the value from the Validate() function.
btnSubmit.OnClientClick = "Getprodsize('" + hdnprdsize.ClientID + "'); formatSpecifications('" + hdnSpecifications.ClientID + "'); Getselectedvalue('" + hdndrop.ClientID + "'); return Validate();";
If you want to check the validation first, and not call the other functions if it fails, you use if
btnSubmit.OnClientClick = "if(Validate()) {Getprodsize('" + hdnprdsize.ClientID + "'); formatSpecifications('" + hdnSpecifications.ClientID + "'); Getselectedvalue('" + hdndrop.ClientID + "'); return true;} else return false";
It would be easier if you moved all this logic out to a new function, and just called that function in OnClientClick.
function validateAndFormat(sizeID, specID, dropID) {
if(Validate()) {
Getprodsize(sizeID);
formatSpecifications(specID);
Getselectedvalue(dropID);
return true;
} else {
return false
}
}
btnSubmit.OnClientClick = "validateAndFormat('" + hdnprdsize.ClientID + "', '" + hdnSpecifications.ClientID + "' + "', '" + hdndrop.ClientID + "');"

not getting to my else in jquery javascript

net mvc application and I am trying to do some validation when someone clicks a button. Here is the code.
function productVerify() {
var intQty = $("#txtQty").val();
var strItemName = $("#item_Name").val();
var strItemDescription = $("#item_Description").val();
var intItemID = $("#item_ID").val();
var intItemPrice = $("#item_Price").val();
var strImgUrl = $("item_ImgUrl").val();
var intQty = $("#txtQty").val();
if (intQty < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
}
else {
//post into cart
alert(strItemName + " " + strItemDescription + " " + intItemID + " " + intItemPrice + " " + strImgUrl + " " + intQty + " " + "I got this far.....! good job")
}
}
this works in jsfiddle but for some reason it does not fully work in my mvc application. it does work on the first if because if I put a 0 in my text box I get the first alert, but nothing happens on the else inside my mvc application. This one part seems so easy, but it is killing me any help would be appreciated.
make sure you using a number in your if statement
//if !num
if (parseInt(intQty) == NaN) {
alert("Please enter a number");
return false;
} else {
//if < 1
if (parseInt(intQty) < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
//if >= 1
} else {
//do something
}
}

addEventListener does not work on "textarea" or "body"

While I'm writing a detect() function for objects, which the user would get a console.log message when they either mouseover or click an element. I got stuck at adding onclick and onmouseover for two elements (or more, but I can't see) : textarea, and body.
The element that works well is label. When I click it or mouseover it, I get a console.log message.
Here is my Code :
function $count(string){
count = count + 1;
if(count <= 9999){
if(count <= 999){
if(count <= 99){
if(count <= 9){
$log("0000" + String(count) + " : " + string);
}else{
$log("000" + String(count) + " : " + string);
}
}else{
$log("00" + String(count) + " : " + string);
}
}else{
$log("0" + String(count) + " : " + string);
}
}else{
$log(String(count) + " : " + string);
}
}
function $detect(obj, type, script){
if(obj.addEventListener){
obj.addEventListener(type, script, false);
}else{
if(window.attachEvent){
window.attachEvent('on' + type, script);
}else{
console.log("Neither window.addEventListener nor window.attachEvent is working.");
}
}
}
Object.prototype.listen = function(){
if(typeof(this) == "object"){
if(this.constructor == Array){
for(var i = 0; i < this.length; i++){
$detect(this[i], 'click', $count(this[i] + " EVENT : onclick"));
$detect(this[i], 'mouseover', $count(this[i] + " EVENT : onmouseover"));
}
}else{
if(isElement(this)){
$detect(this, 'click', $count(this + " EVENT : onclick"));
$detect(this, 'mouseover', $count(this + " EVENT : onmouseover"));
}else{
console.log("ERROR : this.constructor is not 'Object' or 'Array'.");
return null;
}
}
}else{
console.log("ERROR : typeof(this) is not 'Object'.");
return null;
}
return this;
};
When I perform this action :
document.getElementsByTagName("textarea")[0].listen();
I was willing to receive a console.log when I click it or move the mouse above it. However, when I click the textarea, it doesn't produce the console.log.
I guess the problem is at the detect() or listen().
However I did not want to use element.onclick = function(){}; because it will cover the original function, and I cannot add another onclick to it, so using addEventListener should be better.
Where, or which part, should I change my code?
The problem is at the listen() part :
//...
$detect(this, "click", $count("blahblahblah");
I need to wrap $count("blahblahblah") in function(){ }.
That's the problem. That's all.

How to avoid timeout while reading rows from a query (Phonegap + Javascript)

I am trying to insert around 58000 rows of a query inside a string. But after the row around 8000 I get a timeout error.
I've already tried to use SetTimeout funcions but it was of no use.
Check the code that I am working on:
function onQuerySuccess(tx, results) {
console.log("Entering onQuerySuccess");
if(results.rows) {
console.log("Rows: " + results.rows.length);
var len = results.rows.length;
if(len > 0) {
store_html(results, 0);
console.log("Finished Reading Rows: " + len);
saveNotes();
console.log("Finished Saving Notes");
} else {
//This should never happen
console.log("No rows.");
}
} else {
alert("No records match selection criteria.");
}
console.log("Leaving openView");
function store_html(results, rows_complete){
rows_complete=store_html_input(results, rows_complete);
console.log("Returning row:" + rows_complete);
if (rows_complete<results.rows.length)
{
setTimeout(store_html(results, rows_complete), 50);
}
}
function store_html_input(results, rows_complete){
for(var i = rows_complete; i < rows_complete+100; i++) {
gpsTextFile = gpsTextFile + results.rows.item(i).section + ' ' + results.rows.item(i).timestamp + ' ' + results.rows.item(i).latitude + ' ' +
results.rows.item(i).longitude + ' ' + results.rows.item(i).acx + ' ' + results.rows.item(i).acy + ' ' +
results.rows.item(i).acz + ' ' + results.rows.item(i).speed;
gpsTextFile = gpsTextFile + "\n\r";
}
return i;
}
So.. I get that "Javascript execution exceeded timeout".
Thank you for any of your help!
Best Regards.
You need to change your setTimeout() to NOT execute the function immediately. Change from this:
setTimeout(store_html(results, rows_complete), 50);
to this:
setTimeout(function() {store_html(results, rows_complete)}, 50);
As you had it before, it was immediately executing store_html(results, rows_complete) and passing the return value from that to `setTimeout() which was not delaying anything. This is a common mistake (2nd one of these problems I've answered today).

Categories