Customizing Input field to open a numeric link - javascript

If possible i would like to use an input box that i could type "1" to "200" and open the link corresponding to it when applied. All links and input within the same site and folder structure. This would be more favorable than a limited pagination, as well as more mobile friendly.
Full url example to be opened would be: http://example.com/test-1
Currently I have a similar structure with pages that end in "-1" to "-112"
Allowing the following portion pre-determined: "http://example.com/test-"
So that when any number is typed into the input field it would add itself to the pre-determined value listed above. When only "1" or any other number is entered into the field.
Hopefully with compatibility with iOS and most popular browsers. Many Thanks for any help, as i have tried over a dozen other navigation methods, and i feel this would be the best approach. I can do the css and styling of the input, but i'm looking for a light weight approach to handling this query.

This solution works for me. By the way, I like keyboard-input-based interfaces since they are truly the fastest way of navigation yet strangely are not popular in these days of dumbing down people to always push buttons, so I also am voting up your question.
Some features that are important and which I programmed into the code are that this JavaScript navigates without the user needing to push "Go" on their mobile device's keyboard, while also making sure that the user has time to keep typing if they are intending to type a two- or three-digit number.
<input type="text" onkeyup="
if (self.going) clearTimeout(self.going);
var x = this.value.replace(/\D+/g, '');
if (!x) return;
self.going = setTimeout(function() {
var url = 'http://example.com/test-' + x;
/* alert(url); */
location.href = url;
}, 1000);
" placeholder="Enter 1-112!" />
Customization options:
By changing 1000 to a different value, you can customize the slight pause before navigation begins (at risk of prematurely leaving the page before the user has finished typing).

This is pretty straighforward:
<input type='text' placeholder='Enter a number' id='number' />
<input type='button' value='Go' id="go" />
<p>Please enter a number above.</p>
jQuery/JS:
$('#go').on('click', function(event) {
var num = $('#number').val();
if (num == "") return;
var url = "http://example.com/test-" + num;
window.location.href = url;
});
Example
http://codepen.io/hamstu/pen/shdjv

Related

How to set a input text (with no ID or name) value with a subsequent submit of that input text?

I have been trying already all kind of code snippets in Chrome Dev tools on this website:
http://kiwisdr.sk3w.se:8073/?#
This is a software defined radio running on a webserver.
I would like to use Javascript to set the frequency (and submit) so that I can change the frequency the receiver is currently tuned to.
Manually on the GUI the user can just type a frequency (with or without enter) and the new frequeny inside the input box will be tuned.
This is the HTLM part of the website containing the input (no ID or name, so I am not sure how to properly adress this):
<form id="id-freq-form" name="form_freq" action="#" onsubmit="freqset_complete(0); return false;">
<input class="id-freq-input w3-input w3-border w3-hover-shadow" style="padding:0 4px;max-width:74px" size="8" onkeydown="freq_keydown(event)" onkeyup="freqset_keyup(this, event)" type="text" value="" onchange="w3_input_change('undefined', 'undefined')">
</form>
I managed to set the frequency, but I am stuck on how to make it submit.
This is the code I used to set the frequency input box to a certain value (1234.50):
targetForm = document.forms['form_freq'];
targetForm.elements[0].value = '1234.50';
I already tried to trigger the keydown, keyup or change events using some snippets I found, but I am not sure I adress the right elements in the form with it.
All I want to do is to mimic a user entry by code :-)
Could someone point me into the right direction by having a look on the way how the input works on this website and how I can make the website update the currently received frequency with javascript?
Thanks.
Short answer:
freqset_keyup(document.forms[1][0], null)
Nicer answer:
function change_freq(new_freq) {
var form = document.forms['form_freq'];
var freq_input = form.elements[0];
freq_input.value = new_freq;
freqset_keyup(freq_input, null);
}
change_freq(1234.50)

How do I autofill a widget with form inputs using Javascript?

I'm working on a donation form that has a widget embedded in it. The widget opts users into our Mobile Giving giving program which uses separate software than our donation forms. I've been asked to see if we can make the widget invisible but transfer the form data to it and submit it when the user submits the donation form. I've already run into a problem with getting the form data to transfer to the widget though.
The form should get the donors first name, last name and phone number from the form and then autofill the widget when a checkbox is clicked stating that the user would like to receive mobile updates.
Below is what I've tried but it doesn't seem to be working. The code for the form is relatively long so I just included the relevant fields but here is link to the full form: http://support.ddfl.org/site/Donation2?df_id=9442&mfc_pref=T&9442.donation=form1
I'm very new to Javascript so I'm not entirely sure if this is possible. Just an fyi, I also included console statements so I could see if the values were working.
<input type="text" name="billing_first_namename" id="billing_first_namename"
<input type="text" name="billing_last_namename" id="billing_last_namename"
<input type="text" name="donor_phonename" id="donor_phonename"
<input type="checkbox" name="mcoptin" onclick="FillMobileCause(this.form)" value="this.form"> Opt in to receive mobile updates.
Mobile messaging powered by Mobilecause<script>!function(d,s){var s=d.createElement("script"),h=(document.head||d.getElementsByTagName('head')[0]);s.src="https://app.mobilecause.com/public/messaging_widgets/q71xd/source";h.appendChild(s);}(document);</script>
<script>
function FillMobileCause(f){
if(f.mcoptin.checked == true){
console.log(f.billing_first_namename.value);
console.log(f.billing_last_namename.value);
console.log(f.donor_phonename.value);
if(f.billing_first_namename.value.length>=1){
f.firstname.value = f.billing_first_namename.value;
}else {
f.firstname.value = '';
}
if(f.billing_last_namename.length>=1){
f.lastname.value = f.billing_last_namename.value;
}else{
f.lastname.value = '';
}
if(f.donor_phonename.length>=1){
f.mobilenumber.value = f.donor_phonename.value;
}else{
f.mobilenumber.value = '';
}
console.log(f.firstname.value);
}
}
</script>
Please let me know if I'm leaving off important details. This is also my first StackOverflow post. ;)
I appreciate your help!
Your main issue is that you were referring to inputs in the mobilecause form as if they were in the same form, but they are in another (nested in your f main form).
function FillMobileCause(f){
var mcF = f.getElementsByClassName('mc-triggersubscription')[0];
if(f.mcoptin.checked == true){
mcF.firstname.value = f.billing_first_namename.value;
mcF.lastname.value = f.billing_last_namename.value;
mcF.mobilenumber.value = f.donor_phonename.value;
}
}
f is still the main form (the one that is the parent of the checkbox).
But now we have another one, mcF (mobilecauseForm), which is selected using the getElementsByClassName (this will search for a child with the mc-triggersubscription class). The [0] part is so the first match is selected (getElementsByClassName returns an array.
After that, all we need to do is assign the f inputs' values to the mcF ones.
Note: I left behind the "if empty" validation for simplifying. Anyway I don't think it's really needed, if a value is empty, there is no major issue in just copying it to the mobilecause value.

Force iOS numeric keyboard with custom / currency pattern

Is there a possiblity to force an iOS-device to show the numeric keyboard while using a custom pattern as input type?
my input pattern:
<input id="price" class="numeric" pattern="\d+((\.|,)\d{1,2})?" name="price"
title="" data-mini="true" data-clear-btn="true" autocomplete="off" autofocus />
I want to type a currency value like '14.99' and show up a keyboard with access to numbers on the iOS device
<input type='number' />
<input pattern='[0-9]*' />
<input pattern='[\d]*' />
are all missing the decimal sign and/or are not validating as number when adding a decimal sign. An alternative way could be a javascript function which is creating the decimal sign on the right place, like pressing 1->2->9->9 in this order creates on keypress() 0.01->0.12->1.29->12.99,
but this requires the input field to be type='text' --> obvious problem here is that the text keyboard is showed when focussing the input field.
How can I solve this issue?
EDIT
Environment:
JQM 1.3.2
jquery 1.8.2
For now, JavaScript is the only solution. Here's the simplest way to do it (using jQuery):
HTML
<input type="text">
JavaScript
$('input[type="text"]').on('touchstart', function() {
$(this).attr('type', 'number');
});
$('input[type="text"]').on('keydown blur', function() {
$(this).attr('type', 'text');
});
The idea is simple. The input starts off and ends up with type="text", but it briefly becomes type="number" on the touchstart event. This causes the correct iOS keyboard to appear. As soon as the user begins to enter any input or leave the field, the input becomes type="text" once again, thus circumventing the validation.
There's one downside to this method. When the user returns to an input that has already been filled out, the input will be lost (if it doesn't validate). This means the user won't be able to go back and edit previous fields. In my case, this isn't all that bad because the user may want to use the calculator over and over again with different values, so automatically deleting the input will save them a few steps. However, this may not be ideal in all cases.
It looks like Mobile Safari supports the new HTML5 input type attributes of email, number, search, tel, and url. These will switch the keyboard that is displayed. See the type attribute.
So for example, you could do this:
<input type="number" />
And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.
If you really only want numbers, you could specify:
<input type="tel" />
And then the user would get the phone number dialing keypad.
I know this works with Mobile Safari -- I only assume it will work with UIWebView.
http://conecode.com/news/2011/12/mobile-safari-uiwebview-input-types/
I made this little snippet to achieve what you want and I've tested it on iPhone 5 v7.0.3
I used e.which to read CharCode entered and then push it into an array (before) which represents digits before decimal mark and another array (after) to move values from (before) array past the decimal mark.
It might look complicated, due to my humble programming skills.
1) Code demo - 2) Currency conversion demo
HTML:
<input type="tel" id="number" />
JS
Variables and functions:
// declare variables
var i = 0,
before = [],
after = [],
value = [],
number = '';
// reset all values
function resetVal() {
i = 0;
before = [];
after = [];
value = [];
number = '';
$("#number").val("");
$(".amount").html("");
}
// add thousand separater
function addComma(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Main code:
// listen to keyup event
$("#number").on("keyup", function (e, v) {
// accept numbers only (0-9)
if ((e.which >= 48) && (e.which <= 57)) {
// convert CharCode into a number
number = String.fromCharCode(e.which);
// hide value in input
$(this).val("");
// main array which holds all numbers
value.push(number);
// array of numbers before decimal mark
before.push(value[i]);
// move numbers past decimal mark
if (i > 1) {
after.push(value[i - 2]);
before.splice(0, 1);
}
// final value
var val_final = after.join("") + "." + before.join("");
// show value separated by comma(s)
$(this).val(addComma(val_final));
// update counter
i++;
// for demo
$(".amount").html(" " + $(this).val());
} else {
// reset values
resetVal();
}
});
Reset:
// clear arrays once clear btn is pressed
$(".ui-input-text .ui-input-clear").on("click", function () {
resetVal();
});
Result:
I think that you can use the same approach that I suggested to Ranjan.
Using a textfield like a buffer. First you need to detect when the keyboard appears and check if the first responder is the webview. Then you become a textview as the first responder.
When you are setting the text inside the input of the webview, you can add some logic to validate the number.
Here is a link of my example project with the solution, in your case you don't need change the inputView. But the approach is the same, use a Man in the middle.
Cant comment on https://stackoverflow.com/a/19998430/6437391 so posting as a separate answer...
This is the same idea as https://stackoverflow.com/a/19998430/6437391 but instead of switching the type, its the pattern that's switched.
This has the effect of not clearing the value on the textfield on focus when value does not match numeric format, for example, if the value has separators( 1,234.56 ).
$('input[type="text"]').on('touchstart', function() {
$(this).attr('pattern', '[0-9]*');
});
$('input[type="text"]').on('focus', function() {
$(this).attr('pattern', actualpattern);
});

How to make the down arrow work on input search box?

I have a input on my page where I am asking the user to type in any value and based on his entry the values are displayed from the database.
For example if the user types p in the input box he is displayed programmer 1 and programmer 2 just as it does in google.com. This I am doing through ajax.
My problem is after programmer 1 and programmer 2 is displayed, the ↓ Down Arrow key doesn't bring the control to the programmer 1 but rather keeps the control on the search box and the user has to click on any of these options. I want the user to be able to use the ↓ down arrow key to come down to his search suggestions.
I have tried to implement Focus functions but it doesn't seem to work and I don't really know how to look for this information?
Code:
<input type="text" name="searchbox" class="search_input" id="searchboxid" autocomplete="off" autofocus="on" onkeyup="suggest(this.value)" placeholder="Please search here..."/>
Any help will be much appreciated.
Just a suggestion.
Instead of fighting with your own code or going for keybinding stuffs. Its better to use jquery autocomplete.You can easily port your code to fit with Jquery auto complete.Its giving the option what you are expecting.
Refer the URL below.
http://jqueryui.com/autocomplete/
Try with autosuggest or with autocomplete on. If none works , try key binding via hex code for down arrow. It is little dark , but it works in many cases , only prob could be AV's , which could recognise it as a keylogger.
Oke short tell: i'll put in code later (15 minuts)
Html:
<input type=""text id="r0">
<div id="r1">the damn results</div>
<div id="r2">another dman result</div>
Jquery:
$("body").keydown(function (e) {
if (e.keyCode == 38) { //up-arrow
//check wich one is focus
//?????
//r
if ($("#" + rId).length > 0) {
//focus on this element
}
}
if (e.keyCode == 40) { //down-arrow
//check wich one is focus
//?????
//r
if ($("#" + rId).length > 0) {
//focus on this element
}
}
});
Raw i will work it out in a second

How can I dynamically change the style of some text depending on user input?

First, let me start off by saying that I know absolutely nothing about JavaScript or client-side scripting. All of the programming I've ever done has been server-side, mostly PHP, with some Java thrown in too for good measure.
So, I have absolutely no clue where to start with this problem. I have an application with very strict password rules. Users receive a default password when they first are given an account, and must change it immediately. However, no one ever reads the password requirements the first time, and as such, it always takes multiple tries to create a new password.
So, I've created a table like this:
<table>
<tr><td align="right">• Not be the same as your old password</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Not be fewer than eight characters in length</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one number</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one uppercase letter</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one lowercase letter</td><td align="left">Not Met</td></tr>
</table>
//Later on, inside some <form> tags
<tr><td align="right">Old password: </td><td align="left"><input type="password" id="oldpass" name="oldpass" tabindex="1" /></td></tr>
<tr><td align="right">New password: </td><td align="left"><input type="password" id="newpass1" name="newpass1" tabindex="2" /></td></tr>
<tr><td align="right">New password, again: </td><td align="left"><input type="password" id="newpass2" name="newpass2" tabindex="3" /></td></tr>
What I want to have happen is while the user enters text in the fields, JavaScript (I guess) runs in the background and changes the "Not Met" text to "Met" and makes it green or something if the password validates. What is the best way to do this?
TIA.
Off the top of my head, you could create a function that contains all the validation rules you need, e.g:
function validatePass()
{
var error = false;
var oldPass = document.getElementById("oldPass").value;
var newPass = document.getElementById("newPass").value;
if(oldPass != newPass) {
error = true;
}
if(error) {
document.getElementById("someCellId").innerText = 'Not Met';
} else {
document.getElementById("someCellId").innerText = 'Met';
}
//set error to false for the next rule
error = false;
//more rules
//possibly using
//regular expressions
//and referencing appropriate
//not met and met table cells
}
Attach that to the keydown event of all three text boxes, e.g.:
<input type="password" id="oldpass" name="oldpass" tabindex="1" onkeydown="javascript:validatePass()" />
That should be a start.
Depending on what javascript framework you are using (if any), the implementation will be different. But the concept will be the same:
1 - You should observe the onchange event of the given text input where the password is being typed.
2 - When the event is triggered, it should call a function that would validate if the password meets the minimum requirement, so you would also need a function to make that validation.
3 - If it does have the minimum requirements just change the text and style of the specific span.
For Prototype JS it would be something like (imagining that the first table you shown had an id for the DOM parsing):
function isValid(elem){
// example:
if($(elem).value.length < 8) return false;
return true;
}
$('newpass1').observe('change', function(){
if(isValid('newwpass1'){
// it would be easier and faster with an id in the table cell
var elem = $$('table#tableid td')[8];
elem.innerHTML = 'Met';
elem.setStyle({color:'green'});
}
});
You could also use a ready to use solution like jQuery Validation and skip the in-house coding for all this validations.
This would depend on where the validation logic resides (as you mentioned this was a requirement). If you have a server side (asp.net/php/asp/coldfusion, etc) chunk of code (non ajax enabled then you would do this on the "post back" from the user. If you want to do this in java script then you would have to a) have the text validation performed via javascript or use javascript Ajax call to get the validation via the server side of things.
Then, you could use a library like jQuery + CSS to go ahead and change the colors, etc...
I believe in asp.net there are validation controls that will do this for you. Ajax as well.
First problem I see is:
Not be the same as your old password
are you sending the hash of the old password + salt and comparing it? If so you would also have to be sending your salt.
My suggestion is do this on the server side. The other requirements you could do in javascript, but you'd also want to have the same requirements on the server side. So for consistency you'd be better off keeping all of the validation in the server-side.
You can submit via ajax if you really don't want the to load another page, but doing all of the validation in javascript is probably not the best plan
enter code hereYou would need to use events. First you would need to attach an event to the textbox like so,
/* *this* passes a reference of the text box to the validateBox function */
<input type="password" id="oldpass" name="oldpass" tabindex="1" onkeydown="validateBox(this)"/>
I have used onkeydown so that validations happens when user in entering values in the textbox. (for other types of events refer link text)
Now you would need to write your business logic for the validateBox function. It is always a good practice to write this inside the inside section like so,
<head>
....
<script>
function validateBox(currentTextBox) {
/* this passed from the */
if(currentTextBox.id == "blah") {
// to perform validation according to the referenced textbox
if(currentTextBox.value == "blah") {
alert(" met ");
// in practice you would need to create a initially hidden div
//element & populate the content of the div accordingly. & then unhide it.
}
}
}
</script>
</head>
I would strongly suggest using javascript libraries/frameworks like jQuery etc. They make your life very easy & more productive!

Categories

Resources