Character submitted wrong after replace - javascript

i use a greasemonkey script to replace any commas or semicolons from fields.
There are several internal websites where i have to do this, some only with input fields, some with textarea.
The script actually works, but when i submit the form, the replaced characters of the textareas will still get submitted as commas and semicolons.
To be sure that the submit will not be triggered before last blur, i added a alert.
(function() {
'use strict';
$(document).ready(function(){
$("textarea").blur(function(){
this.value=this.value.replace(/[,;]/g, "-");
this.value=this.value.replace(/\n/g, " ");
});
$("input").blur(function(){
this.value=this.value.replace(/[,;]/g, "-");
this.value=this.value.replace(/\n/g, " ");
});
});
var nodes = document.getElementsByTagName('input');
if (window.location.href == "<website-url>")
nodes[39].setAttribute('onclick', 'alert("Data validated")');
else
nodes[0].setAttribute('onclick', 'alert("Data validated")');
Any ideas? Tested with different browsers and different characters.

I'd use the submit event to make sure any lingering changes not handled yet by blur are handled before submission:
$(document).ready(function() {
function updateValue() {
this.value = this.value.replace(/[,;]/g, "-").replace(/\n/g, " ");
}
$("textarea, input").blur(updateValue);
$("form").submit(function() {
$(this).find("textarea, input").each(updateValue);
});
});
Sadly, Stack Snippets don't allow forms, so here's the above live on jsFiddle. Note that if you type, say, cute;kittens into the field and then either tab out of it or submit it, it's changed to cute-kittens and that's the value that gets submitted to Google if you send the form.

Related

How to validate form in Magento Javascript as you type

Magento has awesome Javascript validation library, which can be initialized var myForm= new VarienForm('[your form id]', true);. However this validation function is triggered when one click on submit button.
Is not there way to validate particular field as you type. For example if I type postal code 2 digit and go to second field, it should instantly validate postal code and show error. As postal code require at least 5 digits.
thanks
Yes, Magento provide awesome validation library. You can call validation for each field with `validate' method.
For example to validate zip code, you can observe blur event and call validate method.
$('billing:postcode').observe('change', function(e){
Validation.validate($('billing:postcode'))
})
Notice Validation.validate($('billing:postcode')), this will call validation for postcode field.
First, create for your form.
<form action="<?php echo $this->getUrl('/some/route/thing');?>" id="theForm">
<input type="text" name="foo" id="foo" />
</form>
Next, run this bit of javascript to turn your plain old form into VarienForm
<script type="text/javascript">
//<![CDATA[
var theForm = new VarienForm('theForm', true);
//]]>
</script>
Then, write your validation as a javascript function using the Validation.add method. (Validation is a global used to store all form validation rules)
<script type="text/javascript">
//<![CDATA[
var theForm = new VarienForm('theForm', true);
Validation.add('validate-must-be-baz','You failed to enter baz!',function(the_field_value){
if(the_field_value == 'baz')
{
return true;
}
return false;
});
//]]>
</script>
For more info follow this link.
You can write a custom validation class:
Validation.add('validate-float','Error message',function(v){
return Validation.get('IsEmpty').test(v) || (!/\./.test(v));
});
see - https://magento.stackexchange.com/a/15165/4832
Not adding anything new here, but if you want to cut-and-paste a quick way to create multiple validations for your form, just add to the fields array:
var fields = ['firstname', 'lastname', 'telephone', 'street1', 'region_id', 'country_id', 'city', 'postcode'];
fields.map( function (fld) {
$('billing:' + fld).observe('change', function(e){
Validation.validate($('billing:' + fld))
});
});
Not 100% on how you'd implement it, but you can use Prototypes Event listener. I've tried hooking in to Magento's form validation once before in order to stop multiple form submissions, the code was similar to what's below but I've changed it a bit to fit with your requirements:
new Event.observe('contactForm', 'keyup', function(e){
e.stop();
if(contactForm.validator && !contactForm.validator.validate()) {
//do something here because it failed validation
return;
}
});

How to convert function to MooTools?

We have this code that auto submits our form, when users search but we do not want to use it anymore as its dirty, how can we accomplish this in MooTools?
Thank you
<script type="text/javascript">
function autosubmit() {
setTimeout("document.search_form.submit()", 1000);
}
</script>
<input type='text' class='home_signin_field' id='search' name='user' size='30' onchange="autosubmit()">
We have a autosuggest script that drops down with a list of results when typing in that field, when a result is clicked, it auto inserts text into field, that is the reason for our messy method. The autocomplete script doesn't automatically submit form.
This is our AutoSuggest script:
<script type="text/javascript">
<!--
window.addEvent('domready', function(){
var options = {
script:"results.php?task=suggest_user&limit=3&",
varname:"input",
json:true,
shownoresults:false,
maxresults:5,
multisuggest:false,
callback: function (obj) {
}
};
var as_json = new bsn.AutoSuggest('search', options);
}
);
//-->
</script>
I can simply add onchange="$('search_form').submit(); return false;" to input field, but redirects so quick the full text in field doesn't preserve, so 2 characters are caught after submission (breaking results).
If your <input> is inside a <form> in the html you could use this:
document.id('search').addEvent('change',function(){
this.form.submit();
});
If not, you can call the form directly and use .submit().
If it still doesn't work it might be because your "autosuggest script" does not fire a change event in the input field #search. In that case you could add this in your autosuggest script after the value of the #search input has been set: document.id('search').fireEvent('change');.
Check this demo if it helps.

JavaScript Character Counter Resets to 0 after PostBack

I have this JavaScript that counts character from a textarea which is the code below:
$(document).ready(function () {
$('#count').click(counter);
$('#txtComment').change(counter);
$('#txtComment').keydown(counter);
$('#txtComment').keypress(counter);
$('#txtComment').keyup(counter);
$('#txtComment').blur(counter);
$('#txtComment').focus(counter);
$('#txtComment').focusin(counter);
$('#txtComment').focusout(counter);
$('#txtComment').mousedown(counter);
$('#txtComment').mouseenter(counter);
$('#txtComment').show(counter);
$('#txtComment').load(counter);
$('#txtComment').submit(counter);
$('#btnSubmit').click(counter);
});
counter = function () {
var value = $('#txtComment').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0); // I only use this one.
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length; // I only use this one.
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount); // I only use this one.
$('#charCountNoSpace').html(charCountNoSpace);
};
And I am displaying the counter in a span:
<span id="totalChars">0</span> characters
When the Page is not PostBack, the count seems to be working fine. On the page, I have a submit button which is an ASP.NET control that runs at server. When it comes to the scenario where the button is clicked, the page is doing a PostBack, after submitting the data, It will display the same page, retains the content of the textarea, but, the count sets back to zero even when there are value/s on the textarea. As you can see, I have already put almost all of possible events the form should do.
I need to count the characters and display it after PostBack.
The counter function is not firing until the textarea is interacted with. After binding all your events, call the counter function manually (IE counter();) in your $(document).ready function and the code will be run at page load.
You might think the load event would do this for you, but load only works with elements that have a URL associated with them (like images and scripts, see the documentation for more information).
You can use jQuery Cookies Plug-in to persist, like:
to save: jQuery.cookie("cookie_counter", totalChars);
to get: var totalChars = jQuery.cookie("cookie_counter");
You can change the span tag to run at the server, so the ViewState will persiste the value after the postback.
<span id="totalChars" runat="server">0</span> characters
on the submit button "OnClientClick" event you can call a javascript function.
save the character count in the session.
after page loads completely assign the value stored in session to the span.
you should create a session variable before only to make use of it.
eg. function setVar(){ alert("Testing"); <% Session("TempVar") = "setVar Test" %> }

How to get Javascript to post a form?

I am using the following code:
document.forms["form_name"].submit();
It doesn't seem to work. Is there another way to submit a form using Javascript?
Not really. It probably doesn't work because you have form element named "submit". Change its name and the code will work.
To confirm this is really the problem, some debug is required:
var sFormName = "form_name";
var oForm = document.forms[sFormName];
if (oForm) {
if (oForm.elements["submit"]) {
alert("form contains element named submit, can't use JS to submit it");
}
}
else {
alert("Form named " + sFormName + " does not exist");
}
Keep us updated. :)
If you're in Internet Explorer, there HAS to be a <input type='submit'> present in the form in order to work. May just be IE7, but we've run into that problem.
To hide the button just use style='display:none;'

Input text clear when I try to submit for a search

Hello I have the following problem. I the site http://www.telefonkoll.se when I enter a number in the search and press the button then the text clears automatically and the result page return me all the results. If I don't use the jquery code it works correctly.
My jQuery code is this:
$("document").ready(function() {
$("#mod_search_searchword").attr("value","Sök telefonnummer här");
});
$("#mod_search_searchword").live('focus', function (event) {
$("#mod_search_searchword").focus(function() {
$(this).val("");
});
});
$("#mod_search_searchword").live('blur', function (event) {
$("#mod_search_searchword").blur(function() {
if ($(this).val() == ""){
$(this).val("Sök telefonnummer här"); }
});
});
What I want to do with the above code is to clear the current text when the user click there. If it write something to still there, if not to return the initial text. It looks to work correctly but when I try to submit the data something wrong obviously happen. I don't know if it's the code or something I don't know.
Avoid reinventing the wheel. Use one of the many jQuery watermark plugins available.

Categories