There are several questions/answers on this here, here and here and elsewhere, but they all seem JQuery specific and do not appear to apply to this (for example, I am NOT creating a new Form object, this is an existing form in the document. Also I am NOT using Jquery at all).
I have a form which has to be modified before submission for reasons of IE7 compatibility. I have to strip out all the BUTTON tags from my form and then add a hidden field, but this is all in an existing form on the existing HTML page. This code works properly in IE and Chrome but doesn't work in Firefox (versions 23 & 24 both tested).
buttonClickFunction(formName, buttonObject) {
var formObject = document.forms[formName];
var i = 0;
// Strip out BUTTON objects
for (i=0;i<formObject.length;i++) {
if (formObject[i].tagName === 'BUTTON') {
formObject[i].parentNode.removeChild(formObject[i]);
i--;
}
}
// Create new field
var newField = document.createElement('input');
newField.type = 'hidden';
newField.id=buttonObject.id;
newField.name = buttonObject.name;
if (buttonObject.attributes['value'] != null) {
newField.value = buttonObject.attributes['value'].value;
} else {
newField.value = buttonObject.value;
}
// Submit form
formObject.appendChild(newField);
document.forms[formName].appendChild(newField);
document.forms[formName].submit();
}
In addition to the document.forms[formName].submit() I have also tried formObject.submit() - both work in Chrome but both fail in Firefox. I'm at a loss as to why this doesn't work - I've traced through the JS and watched that document.forms[formName].submit() execute - no exception appears but nothing goes to the server.
Can anyone identify why Firefox won't submit this form, and how I can fix it?
Firefox expects that, when you submit a form, you have at least a submit button available, meaning there should be something like:
<button type="submit">Click me</button>
or:
<input type="submit" value="Click me" />
When you use the first one in your code, it will not work (because you strip out all buttons before submitting the form). When you use the second option, it will work, also in Firefox. As you can see in this fiddle: http://jsfiddle.net/q9Dzc/1/
I had similar behaviour, when form.submit() didn't work on Firefox, but worked on other browsers. Just make sure that all the buttons within form contain type="button".
For anyone having an issue with making the Firefox submit with the page location changing / reloading afterwards, you need to put your redirect code in the $.post callback:
$(".form").submit(function(e){
e.preventDefault();
$.post("submit.php", {data: textData}, function(){
history.go(-1);
});
return false;
});
If your form has a mixture set of "input [type=button]" and "button", the JavaScript of submit() will not work for "input [type=button]" sometimes.
Related
I have an problem with my site when I want to change the css style from the JavaScript it works but only for few seconds.
function validateForm() {
var fname = document.getElementById('<%=UserFnameTextBox.ClientID%>');
if (fname.value == "") {
document.getElementById("WarnUserFnameTextBox").style.opacity = 1;
document.getElementById('<%=UserFnameTextBox.ClientID%>').style.borderColor = "red";
getElementById('<%=UserFnameTextBox.ClientID%>').focus;
}
}
I'm using also Asp.net, that's why I wrote the ID like this
I want that the JS will save the style for as long that the user enter the textbox.
Multiple things here: I suggest that your validateForm() function triggers in an onClick on your submit-button, right? Does your button look somewhat like this?
<input type="submit" value="submit" onClick="validateForm()">
If this is the case, the reason why your styles work only for few seconds is simply that the website reloads. The styles are in effect, but the form is also triggering and send to the site, which you added in your <form action>. After reloading, the website will fall back to its default style, as if the errors never occured... which is correct on that instance of the site.
If you want to have it permanent, you have to disable the submit-button as long as there are invalid fields. You can make use of the required attribute for form elements as well, since the form won't submit as long as there are invalid fields. These can be styled as well.
Have a look at these CSS rules for that:
/* style all elements with a required attribute */
:required {
background: red;
}
You can make use of jQuery as well and disable the form-submit with preventDefault. You can take care of every style and adjust accordingly, as long as there empty / non-valid characters in your input-fields. I suggest combining this with the onKeyUp-function. This way you check everytime the users releases a key and can react as soon as your input is valid.
As an example with jQuery:
var $fname = $('#<%=UserFnameTextBox.ClientID%>');
var $textBox = $('#WarnUserFnameTextBox');
$fname.on("input", function() {
var $this = $(this);
if($this.val() == "") {
$textBox.show();
$this.focus().css("border", "1px solid red");
}
});
(thanks for pointing out my errors and optimizing the code, #mplungjan!).
To "disable" the actual form-submission, refer to this answer:
https://stackoverflow.com/a/6462306/3372043
$("#yourFormID").submit(function(e){
return false;
});
This is untested, feel free to point out my mistake, since I can't check it right now. You can play around on how you want to approach your "errorhandling", maybe switch to onKeyDown() or change(), that kind of depends on your needs / usecase.
Since your question isn't tagged with jQuery, have a look at this answer given by mplungjan as well, since it uses native JS without any framework.
https://stackoverflow.com/a/53777747/3372043
This is likely what you want. It will stop the form from being submitted and is reusing the field and resetting if no error
It assumes <form id="myForm"
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var field = document.getElementById('<%=UserFnameTextBox.ClientID%>');
var error = field.value.trim() === "";
document.getElementById("WarnUserFnameTextBox").style.opacity = error ? "1" : "0"; // or style.display=error?"block":"none";
field.style.borderColor = error ? "red" : "black"; // reset if no error
if (error) {
field.focus();
e.preventDefault();
}
});
});
I've actually seen a few questions about this, most of them are from at least 5 or 6 years ago.
I want to have an input box:
<input id="copy-text" type="text" value="Click this text!">
Here's the JavaScript I've been trying to work with:
document.getElementById("copy-text").onclick = function() {
this.select();
execCommand('copy');
alert('This is a test...');
}
I know my code doesn't work. If I remove execCommand('copy'); then the alert() pops up, but it seems to be hitting an error at that line. I've tried making it this.execCommand('copy'); as well, not really sure what to do here.
Fiddle: https://jsfiddle.net/6v24k4sk/
The idea is that I want the user to click the input box, it will select all the text, and then copy it to the clipboard.
Any ideas?
You should put a document. in front of the execCommand.
document.getElementById("copy-text").onclick = function() {
this.select();
document.execCommand('copy');
alert('This is a test...');
}
Here you can find a working example:
https://jsfiddle.net/9q3c1k20/
edit:
The function also returns whether this functionality is supported in the browser. I think you should check the value, because execCommand still has no final specification and is therefore not guaranteed to work in all browsers.
Use this function with your copy_btn (without onclick function).
function function_name() {
var c = document.getElementById("copy");
c.select();
document.execCommand('copy');
}
I am writing a little Meteor app. There is a textarea in a form, which looks like this:
<form name="comments-form">
<label for="textarea">Comment:</label><br>
<textarea cols="40" rows="10" name="comment_textarea" class="comment_textarea">Write your comment here.</textarea><br>
<button class="btn btn-success js-add-comment">add comment</button>
</form>
In my client.js I have the following code for accessing the value of the textarea:
EVENT_HANDLED = false;
Template.website_item_details.events({
"click .js-add-comment": function(event) {
var comment_text = event.target.comment_textarea.value;
if(Meteor.user()) {
Comments.insert({
created_by: Meteor.user()._id,
text: comment_text,
website_id: this._id
});
}
return EVENT_HANDLED;
}
});
However, when I click the button to add the comment, I get the following console output:
TypeError: event.target.comment_textarea is undefined
["click .js-add-comment"]()
client.js:103
Template.prototype.events/eventMap2[k]</</<()
blaze.js:3697
Template._withTemplateInstanceFunc()
blaze.js:3671
Template.prototype.events/eventMap2[k]</<()
blaze.js:3696
attached_eventMaps/</</</<()
blaze.js:2557
Blaze._withCurrentView()
blaze.js:2211
attached_eventMaps/</</<()
blaze.js:2556
HandlerRec/this.delegatedHandler</<()
blaze.js:833
jQuery.event.dispatch()
jquery.js:4690
jQuery.event.add/elemData.handle()
This seems to be basic form handling, but somehow I can't get that text in the textarea into a variable in my javascript code. I've already tried a multitude of variants of accessing it:
document.getElementsByClass()[0].value
$('.comment_textarea').get(0).val() // there should only be one such text area anyway
event.target.comment_textarea.value;
But none of those work for me, I always get that error. It's almost like the textarea was not part of my html or there is a bug in Meteor, which prevents me from accessing textareas.
I also checked whether there are other things named comment_textarea with a fulltext search on all of my projects clientside files, but there isn't any other.
Am I simply blind and overlooking something? How do I get that text?
What's more is, that although I return false, the browser still reloads the page. Could it be related to the error happening before?
You are using the click event of the button and on that event, the textarea is not available. You need to change the event into submit form. First, put the id into your form, change the button into type submit and change the code into
"submit #your-form-id": function(event) {
event.preventDefault();
var comment_text = event.target.comment_textarea.value;
.....
}
After trying even more desperate ways to access that textarea, I think I know now what's wrong:
// var comment_text = event.target.comment_textarea.value;
// var comment_text = document.getElementByName('comment_textarea').value;
// var comment_text = document.getElementByTagName('textarea')[0].value;
// var comment_text = $('textarea').get(0).val();
// var comment_text = $('textarea').get(0).text();
var comment_text = $('textarea').get(0).value; // finally working!
So it seems that when I use jQuery, I can't use the .val() function as stated in my other answers to many other questions, but for some reason I have to treat it like a normal DOM object and use the attribute value instead of the function .val().
Maybe it's specific to the jQuery version in my Meteor app?
So I will test the following:
var comment_text = $('textarea.comment_textarea').get(0).value;
...
Yes, that also works.
Also it fixes the reload issue. I guess since there was an error, it didn't even get to return false and this is why the website reloaded.
I'm trying to use Jquery in order to validate a form's input. On top of that, I want to auto-fill some fields if they are left blank.
Here is how I proceed :
$(form).submit(function () {
var result = true;
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
if ($("#newStartTime").val().length == 0) $("#newStartTime").val("00:00");
if (!timeRegex.test($("#newStartTime").val())) {
$("#newStartTime").wrap("<div class='error' />");
result = false;
}
return result;
});
What's happening here is that the input is set to 00:00, but the submit is rejected (and the field wrapped as an error). If I re-click on submit, it works fine.
The way I see things, Jquery doesn't treat the modifications made after the 'submit' was called.
If that's the case, is there a way to achieve what I want without using ".submit()" twice ?
If I'm mistaken, what's wrong ?
You can add an event listener on the submit button click
by example :
$('#submit_button').click(function() {
var newValue = $('#field1_real').val();
$('#field1').val(newValue);
$('#form1').submit();
});
Regarding the blank fields, it would be best to have the server handle the default values rather than Javascript. It could provide the defaults when the Form is sent to the browser, or apply defaults if their missing when the browser submits the Form.
It keeps the hack out of your JS, and will still work if JS is disabled.
$(form).submit(function() {
.
.
.
});
Here, form means ID of the form?
If it is Id, try like this
$('#formId").submit(function() {
.
.
.
});
I am designin a shoutbox which is AJAX based.
http://businessgame.be/shoutbox.php
The script works perfectly in google chrome, but other browsers don't act like I expect.
To shout a new message, there is a form which owns a input text field. When pressing enter, the form is being submitted, so I have omitted a submit button since pressing enter is sufficient.
<form method="POST" action="" onsubmit="javascript: return shout();" enctype="multipart/form-data">
<input type="text" style="width: 100%;" name="txtShout" id="txtShout" maxlength="600" autocomplete="off" title="Shout!" placeholder="Shout!">
</form>
The shout function looks like this:
function shout() {
alert("test");
// Post shout and clear textField
if(getLength("txtShout")) {
AjaxUpdate("./includes/shout.php?message=" + getItemValue("txtShout"), refreshShoutBox);
setItemValue("txtShout", "");
}
// Stop submit
return false;
}
Normally, the script should call the shout function, the AJAX would send a request to add the shout and then return false so the form does not get submitted.
But in all browsers except Google Chrome, the form gets submitted anyway. I put in an alert() in the function to check if it was called or a coding mistake but the alert is not being shown.
Well, for some reason, I couldn't get the onsubmit function working in other browsers. Instead of desperately keep looking to fix it a decided to go for a different approach. Now I just added a listener to the text box to check when a key is pressed if it was the enter key and then call that function.
That seemed to work, still had to remove the form though, because otherwise it would get submitted ^^.
So now I got something like this:
function shoutEnterListener() {
// Get object
var domObject = document.getElementById("txtShout");
// Get shoutbox html code
if(domObject) {
domObject.onkeydown = shoutEnter;
domObject.onkeypress = shoutEnter;
}
}
function shoutEnter(e) {
var keyCode;
// Check which key has been pressed
if (window.event) {
keyCode = window.event.keyCode;
} else {
keyCode = e.which;
}
// If enter, shout!
if (keyCode == 13) {
shout();
}
}
The shoutEnterListener() is called in the init function. This also proves that there wasn't a coding error whatsoever but purely the function not being called at all.
If you still find the solution to the previous problem, let me know, because this is a bit tedious and intensive code.