I'm trying to convert a preexisting javascript function into a jQuery function.
The function comes from http://javascript.internet.com/forms/zip-to-state.html
and aims to convert a user-entered zip code into a state. I'm using jQuery 1.3.2, with all the necessary plugins, but I'm not very familiar with jQuery syntax and how to convert this from plain ol' Javascript syntax.
The setState function takes two parameters, the zip code element and the state element, so I'm trying to do something like this:
$('$zip_code').change( function () { setState($(this), $('#state')); });
Any thoughts on this syntax? Thanks, Dakota
function getState(zip) {
if ((parseInt(zipString.substr(zip / 4, 1), 16) & Math.pow(2, zip % 4)) && (zip.length == 5))
for (var i = 0; i < stateRange.length; i += 7)
if (zip <= 1 * stateRange.substr(i, 5))
return stateRange.substr(i + 5, 2);
return null;
}
function setState(txtZip, optionBox) {
if (txtZip.value.length != 5 || isNaN(txtZip.value / 4)) {
optionBox.options[0].selected = true;
alert("Please enter a 5 digit, numeric zip code.");
return;
}
var state = getState(txtZip.value);
for (var i = 0; i < optionBox.options.length; i++)
if (optionBox.options[i].value == state)
return optionBox.options[i].selected = true;
for (var i = 0; i < optionBox.options.length; i++)
if (optionBox.options[i].value == "XX")
return optionBox.options[i].selected = true;
}
You can leave the getState and setState functions just as they are, but you should really read up on jQuery before you go asking questions on how to use it. If you don't even know the syntax, you might want to read up on how to use it.
Like Aberon said, use blur in this situation and change '$zip_code' to '#zip_code', where 'zip_code' corresponds to:
<input type="text" id="zip_code" name="whatever_you_want" />
You also want a select box with an id of 'state':
<select id="state">
... options ...
</select>
Aberon's solution still wont work, however, because it is incomplete...
$('#zip_code').blur( function () { setState($(this)[0], $('#state')[0]); });
You want to get the value from the zip_code input element, thus the val() call. You also want the DOM element for the select box with id == 'state', so instead of using the array returned by $('#state'), you want the first element.
Try it out, I hope this helped.
-Stephen
Unless your zip field is a drop down you would probably be better off using either blur or keyup in your function.
$('#zip_code').blur( function () { setState($(this), $('#state')); });
I also changed $zip_code to #zip_code.
Related
So I have a simple program to change the value of an input field every time you blur it. It logs the already used values in an array, an I use that array to check if it's been used. It practically works as intended, but after a few tries it will return true and logs, yet the value wont change.
Updated Code:
var dftvalue = ['Freddy the Grocer', 'Jack the Fiddler', 'Cane the Sheep Herder', 'Arnold the Fish Monger', 'Luke the Car Salesman', 'Josh the Tailor', 'Carol the Baker', 'Tiara the Nacho Vendor', 'example#email.com', 'Your message here.'];
var logused = new Array(); //create new array to log the used indexs
function setdftvalue() {
var newval = dftvalue[Math.floor(Math.random() * 7)];
if (logused.indexOf(newval) == -1) {
this.value=newval;
logused.push(newval);
console.log(logused);
} else if (logused.indexOf(newval) >= 0) {
setdftvalue();
}
if (logused.length == 8) {
for (i=0; i<=7; i++){
logused.pop();
}
}
}
document.getElementById('formname').onblur=setdftvalue;
JSFIDDLE
https://jsfiddle.net/e5pdz37e/8/
Your approach is unnecessarily complicated. At a high level I would recommend an approach that's more like this:
function setdftvalue() {
if (index === (dftvalue.length - 1)) {
// Shuffle your names array
index = -1;
}
input.value = dftvalue[++index];
}
This way you won't need to use any recursion and make unnecessary function calls. And the only time you'll need to randomize is when you've used up all of your available names.
Here's a working example: http://jsfiddle.net/bvaughn/163mqdeL/
Original answer
After a few invocations, your function will fill up the logused Array, at which point calling it again will do nothing. Actually, worse than nothing - it will recursively call itself without end.
I have this Javascript/jQuery code:
for (i = 0; i < 100; i++) {
if(!(html == $("#chat-box").html()))
{
$("#chat-box").html(html);
console.log("a");
}
}
I have this iterating on a for loop 100 times. You would think that at least after the 1st time it would stop iterating unless one of the two values changed (which they don't), but it does not. I do not know why. I tried using if(htm1 != ...) and that did not work.
I believe using the text() method for your comparison will area the issue:
if(!(html == $("#chat-box").text()))
{
$("#chat-box").html(html);
}
Reason being is that jQuery processes the text to prevent issues with special characters with html(), where as with text() it returns the raw value. If it still doesn't work, console.log() out both method return values and the comparison variable to better visualize.
Your variable html is never being initialized or assigned to. What is it's value? With only the code you provided, it's value is undefined. So when you try to do this:
$("#chat-box").html(html);
What happens is this:
$("#chat-box").html(undefined);
Which has no effect. But if you were to initialize html first, it works:
var html = 'stufffff';
for (i = 0; i < 5; i++) {
if(html !== $("#chat-box").html()) {
$("#chat-box").html(html);
console.log("a");
}
}
Also, you should use !== instead of !=.
I am building a recurring events module to drop into a form, this module has several fields.
I have named and ID'd each of this module using array notation. EG:
id='recurring_event_options[yearly][by_date_day_number]'
In my JS I need to target all fields with the matching id recurring_event_options
I have some JS working nicely that enables (non disabled) fields as needed, but before i run this i need to disable all the fields in this module.
I have been using somthing similar to this to disable the fields:
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}
}
}
As you can see, that going to hit every field in the form - thats not what i want - only to disable the fields that belong to the recurring_event_options parent ID.
I have a feeling I probably cant use [] notation in IDs, so suggestions welcome!
First of all i think it is not a good idea to use [].
You can use a hyphen - or underscore _ to separate the values:
id='recurring_event_options-yearly-by_date_day_number'
Now you can disable:
function disableForm(theform) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (formElement.id.indexOf("recurring_event_options") !== -1) {
formElement.disabled = true;
}
}
}
This should work. but in my opinion it will be much better if you use a class instead:
<input type="text" class="recurring_event_options prop2 prop3" />
because the class attribute is designed to support multiple values, separated by a space
Is there an equivalent of IEnumerable.Any(Predicate<T>) in JavaScript or jQuery?
I am validating a list of items, and want to break early if error is detected. I could do it using $.each, but I need to use an external flag to see if the item was actually found:
var found = false;
$.each(array, function(i) {
if (notValid(array[i])) {
found = true;
}
return !found;
});
What would be a better way? I don't like using plain for with JavaScript arrays because it iterates over all of its members, not just values.
These days you could actually use Array.prototype.some (specced in ES5) to get the same effect:
array.some(function(item) {
return notValid(item);
});
You could use variant of jQuery is function which accepts a predicate:
$(array).is(function(index) {
return notValid(this);
});
Xion's answer is correct. To expand upon his answer:
jQuery's .is(function) has the same behavior as .NET's IEnumerable.Any(Predicate<T>).
From http://docs.jquery.com/is:
Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.
You should use an ordinary for loop (not for ... in), which will only loop through array elements.
You might use array.filter (IE 9+ see link below for more detail)
[].filter(function(){ return true|false ;}).length > 0;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
I would suggest that you try the JavaScript for in loop. However, be aware that the syntax is quite different than what you get with a .net IEnumerable. Here is a small illustrative code sample.
var names = ['Alice','Bob','Charlie','David'];
for (x in names)
{
var name = names[x];
alert('Hello, ' + name);
}
var cards = { HoleCard: 'Ace of Spades', VisibleCard='Five of Hearts' };
for (x in cards)
{
var position = x;
var card = card[x];
alert('I have a card: ' + position + ': ' + card);
}
I suggest you to use the $.grep() method. It's very close to IEnumerable.Any(Predicate<T>):
$.grep(array, function(n, i) {
return (n == 5);
});
Here a working sample to you: http://jsfiddle.net/ErickPetru/BYjcu/.
2021 Update
This answer was posted more than 10 years ago, so it's important to highlight that:
When it was published, it was a solution that made total sense, since there was nothing native to JavaScript to solve this problem with a single function call at that time;
The original question has the jQuery tag, so a jQuery-based answer is not only expected, it's a must. Down voting because of that doesn't makes sense at all.
JavaScript world evolved a lot since then, so if you aren't stuck with jQuery, please use a more updated solution! This one is here for historical purposes, and to be kept as reference for old needs that maybe someone still find useful when working with legacy code.
Necromancing.
If you cannot use array.some, you can create your own function in TypeScript:
interface selectorCallback_t<TSource>
{
(item: TSource): boolean;
}
function Any<TSource>(source: TSource[], predicate: selectorCallback_t<TSource> )
{
if (source == null)
throw new Error("ArgumentNullException: source");
if (predicate == null)
throw new Error("ArgumentNullException: predicate");
for (let i = 0; i < source.length; ++i)
{
if (predicate(source[i]))
return true;
}
return false;
} // End Function Any
Which transpiles down to
function Any(source, predicate)
{
if (source == null)
throw new Error("ArgumentNullException: source");
if (predicate == null)
throw new Error("ArgumentNullException: predicate");
for (var i = 0; i < source.length; ++i)
{
if (predicate(source[i]))
return true;
}
return false;
}
Usage:
var names = ['Alice','Bob','Charlie','David'];
Any(names, x => x === 'Alice');
How can I use these JavaScript math functions ?
For example, I want to compute the square of all <input> values in a form, without submiting the form.
Can you give a little example? Thank you.
JQuery doesn't need to support math functions as it is an addon library for Javascript, you can still use Javascript in your JQuery code, so you can still use all the native math functions.
Examples:
Addition
var x = 1;
var y = 2;
var lol = x+y;
alert(lol);
Subtraction
var x = 10;
var y = 1;
var lol = x-y;
alert(lol);
Edit: Now we understand your question a little better...
<input type="text" id="field1" value="16" />
<input type="text" id="field2" value="25" />
<input type="text" id="field3" value="36" />
var field1Value = document.getElementById("field1").value;
var field2Value = document.getElementById("field2").value;
var field3Value = document.getElementById("field3").value;
alert(Math.sqrt(field1Value ));
alert(Math.PI * field2Value);
alert(Math.sin(field3Value));
You can act on each individual input using an each()(docs) loop.
Click here to test a working example. (jsFiddle)
$('a.square').click(function() {
$('#myform :text').each(function() {
this.value *= this.value;
});
});
$('a.square_root').click(function() {
$('#myform :text').each(function() {
this.value = Math.sqrt(this.value);
});
});
When either link is clicked, it finds all the text inputs in myform and iterates over them.
Inside the each function, this refers to the current input element.
JavaScript is the programming language, not jQuery, which is a library for web application programming written in JavaScript. To effectively use jQuery, you need to know JavaScript.
It is, however, possible to use jQuery's functionality to easily work with multiple textboxes at once:
// Set each single-line textbox's value to the square
// of its numeric value, if its value is in fact a number.
$('input:text').each(function() {
var num = +this.value;
if(!isNaN(num)) {
this.value = num * num; // or Math.pow(num, 2)
}
});
It would be quite useful if jQuery had a reduce() function.
When dealing with lists of data, most functional languages, and indeed most traditional languages these days, have methods that perform a repetitive function over the entire list, taking each element in turn and applying a function to it.
The simplest of these is map, which jQuery implements for you. This takes a list and applies a function to each element and returns the list of results, one result per entry in the list. eg. [1,2,3] -> (map x2) -> [2,4,6].
Sometimes you want a total or collective result from a list, rather than a list of individual mappings. This is where the reduce (or fold) operation comes in. Unfortunately jQuery does not have this method available as standard, so below is a plugin for it. A reduce function takes an accumulator value and the value of the current element, and returns the modified accumulator, which will be passed on to the next call. eg. [1,2,3,4] -> (reduce + [initial:0]) -> 10 = ( ( ( (0 + 1) + 2 ) + 3 ) + 4 ) or ([1,2,3,4] -> (reduce * [initial:1]) -> 24 = ( ( ( (1 * 1) * 2 ) * 3 ) * 4 ).
(function($) {
$.reduce = function(arr, callback, initial) {
var accumulator = initial || 0;
$.each(arr, function(index, value) {
accumulator = callback(accumulator, value, index);
});
return accumulator;
}
})(jQuery);
Then you can use it like this to get a sum of squares:
var answer = $.reduce($('input:text'), function(acc, elem) {
var cVal = $(elem).val();
return acc + cVal * cVal;
}, 0);
i was looking for a solution too , and i saw a lot of questions here that doesn't work (even this one) in case someone wondering like me , here is my working solutiuon :
$("#apport").keyup(
function(){
var apport = parseFloat($("#apport").val());
var montant = parseFloat($("#montant-financer").val());
var moinmontant = parseFloat(montant) - parseFloat(apport);
$("#montant-financer").val(moinmontant);
}
);
All the id's selector are input
Use the jquery map function to create an array
$('input:text').map(function() {
return this.value * this.value; // math calculation goes here
}).get();
See a live example
Looking at the initial question that was posted, it clearly states compute the square of all values in a form, without submiting the form.
i think keyup would be the best solution.
$("input").keyup(function () {
var value = $(this).val();
var x=value*value;
$("p").text(x);
}).keyup();
Click here to check the working example.
http://jsfiddle.net/informativejavascript/Sfdsj/3/
For more details visit http://informativejavascript.blogspot.nl/