object.onsubmit event is not activating - javascript

first my code, all in one .hbs file:
<form id='specialform'>
<input name='about' type='hidden'>
<div id='editor'><p>Type something :D</p></div>
<button type='submit'>Reload</button>
</form>
<script>
var form = document.querySelector('#specialform');
form.onsubmit = function() {
var about = document.querySelector('input[name=about]');
about.value = JSON.stringify(quill.getContents());
console.log('Submitted!');
console.log('Submitted!', 'Serialized:', $(form).serialize(), 'Serialize Array:', $(form).serializeArray());
alert('Open Console!');
return false;
}
</script>
Now when I'm trying to press the submit button while testing, nothing happens instead of the expected console.log(...).
I looked everywhere for an answer, hope you guys can help me. I'm just learning node.js and quilljs and it's pretty difficult.
Thanks for the help. I got the code from this preset https://quilljs.com/playground/#form-submit.
EDIT: Fixed the document.querySelector('specialform') to document.querySelector('#specialform'), still does not work.
EDIT2: Function is now closed with }, just forgot it when copying the code. Problem still persists.
EDIT3:
Made a dummy function:
form.onsubmit = function() {
alert('This one works');
console.log('Submitted!');
return false;
}
Which did NOT work without the return false; statement, but DOES work with it! I changed the original function and included the return, but it still does NOT work sadly.
EDIT4:
I played around with the dummy function some more and have isolated the problem.
It stems from this line:
console.log('Submitted!', 'Serialized:', $(form).serialize(), 'Serialize Array:', $(form).serializeArray());
Can someone tell me why it does not work? :)
One can ignore the problem with that line if one does: function (e) { e.preventDefualt(); ... }, but the change only "goes around"(?) the problem and does not fix it.
EDIT5:
With e.preventDefault() the function works, but there is still no 2nd console.log. So apparently handlebars has a problem with the $(form).serialize(), or I'm just too stupid to see my error. Thanks everyone who helped me anyway!
EDIT6:
ISSUE SOLVED! $.(form).serialize() uses the jquery library which is not that easy to work with in node.js and obviously has to get imported first. I thank everybody who helped me solve it!

try this
var form = document.querySelector('#specialform');
you've missed a hash while using the id selector

document.querySelector needs a valid CSS selector.
document.querySelector('specialform');
is saying, hey JS -- get all specialform elements. If you had <specialform><!-- content goes here --></specialform> elements on your page, then that would work.
Instead, you probably want
document.querySelector('#specialform');
That's saying, hey JS -- get all elements with an ID of specialform.

var form = document.getElementById('specialform');
If you know that you are serching by id than i would use this.
Its faster than query, because it doesnt take care about classes attributes and so on.
And its less error prone if you are unsure about query selectors.
In my opinion the querySelector makes more sense if your structure is more complex.

Related

DOM change - no effect. Effect visible only if changed with timeout

Weird problem. I'm modifying shop template:
https://demo.themeisle.com/shop-isle/product-category/clothing/dresses/
At this moment when you hover product's picture there will show "add to cart" button. This is .
Under picture there is price
I prepared code:
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
Nothing happens. This code work only if I set timeout:
setTimeout(function() {
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
}, 10000);
Of course timeout it's not a solution. I was trying to find out minimal time to obtain best behavior but it's impossible. I have feeling that every browser (and version...) needs personalized time setting.
I thought that after 24-hour break I will get some brillant idea, but that doesn't work, no more ideas.
--- EDIT ---
OK, thanks for pointed mixed common js with jquery - I will correct that later.
jQuery(document).ready(function(){
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
console.log(el);
});
});
That's logical that var from should be inside ready but this still doesn't work. No effect.
If I use in loop console.log it will return for me html code of el.
--- EDIT ---
Thanks. While testing I noticed something. I wanted append element .woocommerce-Price-amount.amount to element .product-button-wrap. But how can I do that if element .product-button-wrap isn't originally in source? This object is created dynamically (I don't know how).
-- EDIT --
OK. I checked JS files and found code adding to DOM .product-button-wrap so I putted my code there and now everything works. Thanks for help.
The problem is because you're running your code before the DOM has loaded. You need to retrieve the elements within the document.ready event handler.
Also note that you have an odd mix of native JS and jQuery methods. I'd suggest using one or the other, like this:
jQuery(function($) {
$('.woocommerce-Price-amount.amount').each(function() {
$(this).parent().parent().find('.product-button-wrap').append(this);
});
});
Also note that .parent().parent() should be replace by a single call to closest(), but I can't give you an exact example of that without seeing your HTML.

jQuery plugin letter-fx - add setTimeout

I downloaded the jQuery plugin letter-fx (http://tuxsudo.com/code/project/letterfx) and really like what it can do.
However, on my landing page I'm trying to make the different paragraphs appear in sequence. I thought the best way to do that is to delay each paragraph with setTimeout()
I'm a JS/jQuery novice and hoping someone can help me out. Here's the code I have thus far:
$(function(fx1){
$(".fx1").letterfx({"fx":"fade","backwards":false,"timing":50,"fx_duration":"1000ms","letter_end":"restore","element_end":"stay"});
});
$(function(){
setTimeout(fx1,3000);
});
Can anyone show me what I'm doing wrong? Thanks!
Try below code. To use setTimeout you need to pass a function as first param.
$(function(){
var applyAnimation = function(){
$(".fx1").letterfx({"fx":"fade","backwards":false,"timing":50,"fx_duration":"1000ms","letter_end":"restore","element_end":"stay"});
};
setTimeout(applyAnimation,3000);
});

Error with regex in jquery

I want to validate my textbox on keypress event. As I am newbie with jquery, I searched on google and found one jquery plugin named 'limitkeypress'.
This is my code:
$(document).ready(function() {
$("#title").limitkeypress({ rexp: /^[A-Za-z]*$/ });
});
Plugin library is:
http://brianjaeger.com/process.php
It's giving me the following error
$("#title").limitkeypress is not a function
When I checked the library on jsfiddle it shows me dozens of errors. Is there any other validation library or plugin?
EDIT Thanks everyone for your valuable comment. Finally I got the solution. Though I was including file correctly. but don't know Y it was not working. I wrote jQuery.noConflict(); and all the problem is solved. What exactly it work. Please let me know, though I read but doubt still I have doubt.
regexp is ok:
'buGaGa'.match(/^[A-Za-z]*$/);
$("#title").limitkeypress is not a function probably you forget to inlude library or wrong path.
Check it in Firebug( Net -> All ) lib must be highlight in black, not red.
Made a demo: http://jsfiddle.net/tTASy/
plugin seems to work fine.
Check your path to the script. if you paste a link to your page we could help you more specifically.
You can do this in jQuery like this without the plugin..
$("#your_textbox").keypress(function() {
var length = this.value.length;
if(length >= MIN && length <= MAX) {
$("#your_submit").removeAttr("disabled");
$("#your_validation_div").hide();
} else {
$("#your_submit").attr("disabled", "disabled");
$("#your_validation_div").show();
}
});

jQuery - Click on X, grab the NAME, then use that to show a related element

Here's what's happening.
My page loads. Then jQuery loads a feed which is injected into a contentCol div...
in that feed is:
Comment
There is also:
<div class="storyItemComments" id="storyItemComments_66" style="display:none;">....
For some reason this is not working:
$(".commentWrite").live("click",function(){
cmt2open = $(this).attr('name');
$("#" + cmt2open).show();
return false;
});
Any ideas? The only thing I can think of is that it has something to do with the fact that I am using jQuery AJAX to load in the content which the LIVE statement above is referencing....
thanks
on most occasions people should use the die() function before the live... so that will clear any previews instructions and that function is only triggered once...
another thing could be that the instructions are called before the contents are retrieved from the ajax. therefore you should use .success to check if the ajax was successfully loaded and then trigger the click instructions.
as it seems that the <div id="storyItemComments_66" has not been picked up from the DOM.
Following from your comment to this answer
Can you try the following instead of show()?
$("#" + cmt2open).attr('display', 'block');
Can you place your javascript inside;
$(document).ready(function(){
//your code here
});
Not sure this will fix it but it's good practice I find.
Also have you alerted out your variables to see what you get?
What is the error you are getting if any?
Have you tried putting an alert at the top of the function to see if the click event works?
edit
let me know if the above does not fix it and I'll remove this answer to clear out the noise

.click function not working for me

I have lots of jquery functions in my script but a particular one is not working, this is my function
$('#delete').click(function() {
var id = $(this).val();
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=delete&id=' + id ,
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$(this).parent('tr').slideUp('500').empty();
}
});
});
a similar function like this is working
<!-- WORKING FUNCTION -->
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#table').slideUp('1000').load('data.php #table', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
I checked with firebug, the console doesnt show any errors, i checked html source the values are loading correct, i checked my php file 5times it is correct can't figure out the problem. Please Help.
I struggled with the EXACT SAME PROBLEM for 6hr straight! the solution was to use jquery 'live'.
And that is it.
$('#submit').live('click',function(){
...code...
});
With the first one, I'd put a quick and nasty alert() within the click anonymous function, to ensure that it is being fired. Eliminate reasons why it may not be working. Also, try using Live HTTP headers or Firebug's console to see if the AJAX request is being sent.
If the click is not being fired, see if you have the selector correct. I often do this (quite nasty)
var testSelector = 'p:first ul li:last';
$(testSelector).css( { border: '1px solid red' } );
It won't always be visible, but if you see style="border: 1px solid red"` in the generated markup, you know your selector is on the ball.
Perhaps you have another click that is overwriting it? Try using
$('#delete').bind('click', function() {
// do it
});
I just had the same problem with a quick example I was working on. The solution was to put the click inside $(document).ready. I was trying to use my element before it was actually ready to be used.
It's basic JavaScript to wait until the DOM is ready before you try to use an element, but... for whatever reason I forgot to do that, so maybe the same happened to you.
$(document).on('click', '#selector', function(){
// do something
});
jQuery 1.7+ has depreciated .live() and now uses .on() instead :)
I don't know if this applies in your context, but if you have parts of the page that are getting loaded by AJAX then you'll need to bind the click handlers after that content is loaded, meaning a $(document).ready isn't going to work. I've run into this problem a number of times, where certain events will fire fine until parts of the page are reloaded, then all the sudden the events seem to stop firing.
Just use your .click with $(document).ready(function(){ ... }); because you are trying to apply the click event on a non-existent element.
1) just before the last }); you should add return false;
2) Are you sure that #delete exists? Also, are you sure is UNIQUE?
This is a long shot, but it's good to be aware of.
http://code.google.com/p/fbug/issues/detail?id=1948
May not be an issue if you're not on Firefox 3.5.
Instead of id=delete i changed it to class=delete in html and in js ('.delete') and it is working fine now but when again tried with id it doesnt work.
Thank You all for Help, i dont have any problem whether it is id or class just the function works now.
There is few things you can do:
like Elmo Gallen and Shooz Eh suggested, put your code in $(document).ready(function(){...});
code your $('#delete').click(function(){...}); event handling AFTER your <button> tag,
use $('#submit').live('click',function(){...}); like Parikshit Tiwari suggested.
Everyone of these should work ok.
EDIT: oops, didn't see that this was asked '09 :D
I think you must use .on() function for dynamically code run in jQuery like this:
$(document).on("click","#delete",function(){ });

Categories

Resources