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.
Related
I have a script that works fine when a button is used to post the form. But when I convert the form to (auto)post on an interval, the form (field) values are missing when posted.
I know this has something to do with using the closest(form) as the button assists with closest (form) as a reference, but auto post on Interval has no reference for closest (form). Any help is appreciated thanks. By the way my form is on a sql while loop.
A) is the script when used with button.
B) is the script when used with a Auto(post) on interval.
The form)
<form class="updateform" action="" method="" >
<input type="hidden" class ="customerid" name="" value="<?php echo $customerid?>">
<a class ="test" >test</a>
<div class="update"> </div>
</form>
** A)**
<script>
$(document).ready(function(){
$('.test').click(function(event){
event.preventDefault();
var form = $(this).closest("form");
var field1= form.find('.customerid').val();
// Url to post to and Field name and content */
$.post('/test4.php', {customerid:field1},
// Alert Success
function(data){
// Alerts the results to this Div
form.find('.update').html(data);
});
});
});
</script>
** b)**
<script>
$(function() {
var form = $(this).closest("form");
var field1= $('.customerid').val();
function update() {
$.post("/test4.php", {customerid:field1},
function(data){
$('.update').html(data);
});
}
setInterval(update, 3000);
update();
});
</script>
It's probably because of the .closest() method in the second script. You are trying to select the form there which is closest to this up the tree. But in this case this will either be the scope of the function or the window object. Change it to a jQuery selector and select the correct form.
You can test this by yourself by either using console.log or the debugger statement to check what the values of the elements are in the developer tools of the browser. Get familiar with these guys, you'll need them a lot and are essential tools to even the most experienced developer.
If I may give a tip. Name your jQuery elements (the elements you select with $('element')) with a $ prefix. This way you know by reading the variable what kind of value that variable has. Also giving your variables meaningful names makes it even more easy to read and understand. field1 is generic, but customerIdField tells you what field it is.
$(function() {
var $form = $('form.updateform');
var $updateField = $form.find('.update')
var $customerIdField = form.find('.customerid');
var customerIdValue = $customerIdField.val();
function update() {
$.post("/test4.php", {customerid: customerIdValue}, function(data) {
$updateField.html(data);
});
}
setInterval(update, 3000);
update();
});
I want to focus on specific id (ex. using $('#a')) after submit.
There is nothing special with my code yet.
My javascript code is
function get_info(id){
$(user_id).submit();
$('#a).focus();
};
After submit, it should focus on where id='a'.
But after submit window focus on id='a' and reset the page.
I tried using
function get_info(id){
$(user_id).submit(function(e){
e.preventDefault();
$('#a').focus();
});
};
But this code make program worse. I think it stops performing submit.
Can anyone help me?
As Chris's comment says you couldn't focus on the element simply by using $('#a').focus(); after the submit since the page will be redirected/refreshed.
You need to use cookies or local storage, here a suggested sample using local storage like :
function get_info(id) {
localStorage.setItem('focusItem', '#a');
$(user_id).submit();
};
Then in the ready function, you could add :
$(function(){
var focusItem = localStorage.getItem('focusItem');
if( focusItem != null ){
$(focusItem).focus();
localStorage.removeItem('focusItem');
}
});
function SetFocus(){
$("#FocusingID").focus();}
/***********another way **********************//*
$("#submitbtnId").click(function(){
//your submession and other task;
$("#FocusingID2").focus();
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=FocusingID>
<button type=submit onclick="SetFocus();">click</button>
Say I visit a website which has the following code:
<input type="text" name="enter">
<input type="submit" name="button">
<a id="confirm">Confirm</a>
I need a script which I can run in the Chrome console to press the <a> element then type the text 'hello' into the input field and then click submit. I need this process to repeat every minute.
I have tried using this code.. but it doesn't do anything.
window.setInterval(function() {
document.querySelector("#confirm").click();
document.querySelector(".enter").value = "Hello";
document.querySelector(".button").click();
}, 1000);
If the inputs are placed in a form try this, in this case if you need to access by the name and not the class:
window.setInterval(function() {
var form = document.forms[0];
document.querySelector("#confirm").click();
form.querySelector('input[name=enter]').value ="Hello";
form.querySelector('input[name=button]').click();
}, 1000);
Otherwise your script above will work if the inputs have these correct class names
Instead try using trigger as:
$(document).ready(function() {
var event = JQuery.Event("click");
$('#confirm').click(function() {
$('.enter').value("Hello");
$('.button').trigger(event);
});
$('#confirm').trigger(event);
});
Now just put the code inside your window.setInterval() function.
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;
}
});
This is a followup question to this question:
select all contents of textbox when it receives focus (Javascript or jQuery)
Basically I am using a textbox in conjunction with the jQuery masked input plugin(Edit: Link may no longer point at relevant version)
When the masked input textbox receives focus I want to select all of the contents of that textbox, but it seems as though having this plugin binded to the textbox prevents that. I was just wondering if there was a way around this.
Below is a sample .html page that demonstrates the issue:
<html>
<head>
<title></title>
</head>
<body>
<input id="masktest" type="text" value="01/01/2009" />
<br />
<input id="focustest" type="text" value="on focus will select all contents..." />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script>
<script type="text/javascript">
$(function() {
$("#masktest").mask("99/99/9999");
// Contents of textboxes will be selected when receiving focus.
$("input[type=text]")
.focus(function() {
$(this).select();
});
});
</script>
</body>
</html>
I'm the author of the Masked Input Plugin for jQuery. I decided that this should be the default behavior for completed masks and I got it into the latest release. You can read the details here
Hey Jon, not too sure about the performance of this, but this should work:
$(function() {
// Contents of textboxes will be selected when receiving focus.
$("input[type=text]")
.focus(function() {
var mask = "99/99/9999";
$(this).unmask(mask).select().mask(mask);
});
});
its working for me in FF3.
$("input[type=text]").focus(function(e) {
var that = this;
setTimeout(function(){$(that).select();},10);
return false;
});
setTimeout will "queue" the select() execution, I was wondering about:
- Ok mask functions do your work THEN I'll select the content. That THEN is where the queue is useful.
Just an idea. I hope it works as expected.
Problem
Defaut value is deleting when focus
Resolve : added little patch code to mask.js file (jquery.maskedinput-1.2.2.min.js)
(function(a){var c=(a.browser.msie?"paste":"input")+".mask";var b=(window.orientation!=undefined);a.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"}};a.fn.extend({caret:function(e,f){if(this.length==0){return}if(typeof e=="number"){f=(typeof f=="number")?f:e;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,f)}else{if(this.createTextRange){var g=this.createTextRange();g.collapse(true);g.moveEnd("character",f);g.moveStart("character",e);g.select()}}})}else{if(this[0].setSelectionRange){e=this[0].selectionStart;f=this[0].selectionEnd}else{if(document.selection&&document.selection.createRange){var d=document.selection.createRange();e=0-d.duplicate().moveStart("character",-100000);f=e+d.text.length}}return{begin:e,end:f}}},unmask:function(){return this.trigger("unmask")},mask:function(j,d){if(!j&&this.length>0){var f=a(this[0]);var g=f.data("tests");return a.map(f.data("buffer"),function(l,m){return g[m]?l:null}).join("")}d=a.extend({placeholder:"_",completed:null},d);var k=a.mask.definitions;var g=[];var e=j.length;var i=null;var h=j.length;a.each(j.split(""),function(m,l){if(l=="?"){h--;e=m}else{if(k[l]){g.push(new RegExp(k[l]));if(i==null){i=g.length-1}}else{g.push(null)}}});return this.each(function(){var ORJ=$(this).val();var r=a(this);var m=a.map(j.split(""),function(x,y){if(x!="?"){return k[x]?d.placeholder:x}});var n=false;var q=r.val();r.data("buffer",m).data("tests",g);function v(x){while(++x<=h&&!g[x]){}return x}function t(x){while(!g[x]&&--x>=0){}for(var y=x;y<h;y++){if(g[y]){m[y]=d.placeholder;var z=v(y);if(z<h&&g[y].test(m[z])){m[y]=m[z]}else{break}}}s();r.caret(Math.max(i,x))}function u(y){for(var A=y,z=d.placeholder;A<h;A++){if(g[A]){var B=v(A);var x=m[A];m[A]=z;if(B<h&&g[B].test(x)){z=x}else{break}}}}function l(y){var x=a(this).caret();var z=y.keyCode;n=(z<16||(z>16&&z<32)||(z>32&&z<41));if((x.begin-x.end)!=0&&(!n||z==8||z==46)){w(x.begin,x.end)}if(z==8||z==46||(b&&z==127)){t(x.begin+(z==46?0:-1));return false}else{if(z==27){r.val(q);r.caret(0,p());return false}}}function o(B){if(n){n=false;return(B.keyCode==8)?false:null}B=B||window.event;var C=B.charCode||B.keyCode||B.which;var z=a(this).caret();if(B.ctrlKey||B.altKey||B.metaKey){return true}else{if((C>=32&&C<=125)||C>186){var x=v(z.begin-1);if(x<h){var A=String.fromCharCode(C);if(g[x].test(A)){u(x);m[x]=A;s();var y=v(x);a(this).caret(y);if(d.completed&&y==h){d.completed.call(r)}}}}}return false}function w(x,y){for(var z=x;z<y&&z<h;z++){if(g[z]){m[z]=d.placeholder}}}function s(){return r.val(m.join("")).val()}function p(y){var z=r.val();var C=-1;for(var B=0,x=0;B<h;B++){if(g[B]){m[B]=d.placeholder;while(x++<z.length){var A=z.charAt(x-1);if(g[B].test(A)){m[B]=A;C=B;break}}if(x>z.length){break}}else{if(m[B]==z[x]&&B!=e){x++;C=B}}}if(!y&&C+1<e){r.val(ORJ);w(ORJ.length,h)}else{if(y||C+1>=e){s();if(!y){r.val(r.val().substring(0,C+1))}}}return(e?B:i)}if(!r.attr("readonly")){r.one("unmask",function(){r.unbind(".mask").removeData("buffer").removeData("tests")}).bind("focus.mask",function(){q=r.val();var x=p();s();setTimeout(function(){if(x==j.length){r.caret(0,x)}else{r.caret(x)}},0)}).bind("blur.mask",function(){p();if(r.val()!=q){r.change()}}).bind("keydown.mask",l).bind("keypress.mask",o).bind(c,function(){setTimeout(function(){r.caret(p(true))},0)})}p()})}})})(jQuery);
if your 'completed' function doesn't work, try to replace this line:
if (settings.completed && next == len)
(this is line number 169 of noncompressed plugin) with that:
if (settings.completed && eval(+next - 1) == len)
While using this plugin with firebug, i've noticed, that 'next' variable jumps up over a symbol when last char of mask entered.
This way should work.
I found a better solution than timeout.
You can view jquery.maskedinput.js:293 there is a function for input focus and it is triggered only on inputs without "readonly" attribute so:
$("input[type=text]").attr("readonly", true).select().removeAttr("readonly");
...just like that. Works like a charm ;)