Change an input when you change another one in javascript - javascript

Hard to define the title ^^
I want to have to input fields. For example: one where you type in a color (string) and another for the code of the color (varchar).
Like this: |Green| |#657EC9| (just random color-code)
I do not want to learn how to find the color-code but how to match a value or variable with another. It was just an example.
What i wanna know is how I in the best way auto generate one of the fields when I fill in the second. When I type 'green' in the first field I want the code to automatically appear in the second and vice versa. I just want to do it for a few colors.
I am very new to PHP, HTML and Javascript and could need some good advice about how I should handle the problem.
Thank you

I would tend to just map values to an object literal, so:
var colors = {
Green:'#657EC9',
Red:'#00ffff'
}
Now you could get your value with colors[fieldInputVal] where fieldInputVal might be 'Green' or 'Red' although of course you'd have to test if there actually was a property there. Object literals are the main reason I rarely find a use for switch statements in JS.
As for the event JS, I'm going to be lazy and go with JQuery rather than explain attachEvent vs. addEventListener which would be necessary if you're supporting IE8 or below. If you want to normalize for that yourself and skip JQuery, look up 'addEvent contest' on quirksmode.org
$('.input_one').change( function(){
//note: only fires after the field loses focus - you tab out or focus another field
var inputVal = $(this).val();
if(colors[inputVal] !== undefined){
$('.input_two').val(colors[inputVal]);
}
} );
note: I did not test this code for syntax goofs.
If you want to be more flexible and accept 'green' or 'Green', I would just capitalize the first character before you use it for the lookup. To do the lookup on every character add, you'd have to look up the keyup or keydown events (I prefer keyup to avoid breaking the browsers back when somebody holds a key down).

Related

Using Regex to validate user input as CSS?

I am writing a program that allows the user to create a page using a drag-n-drop GUI. Every element (image, text, etc) will have easy-to-use CSS selectors like background-color and font-size, however my client has asked for the ability, when necessary, to add custom CSS to the element as a final option.
Looking past the dangers of users possibly typing in and saving valid javascript functions, trying to style the body tag etc. (I will make sure to handle that by escaping/PDO-handling user input in PHP), how can I write a regex (or another functionality) that tests, crudely, if what the user types in is valid CSS. My regex at the moment is this:
([A-Za-z\-]+?:\s*?[A-Za-z\-]+?;)+?;
And I run it using
var reg = /([A-Za-z\-]+?:\s*?[A-Za-z\-]+?;)+?/;
if (reg.test(textarea.val())) {
console.log("yay");
//add CSS to element
} else {
console.log("nay");
//let user know their input is wrong
}
This works fine to validate
css-selector: css-value;
However, anything after that it will still validate as true because the first part will be true:
css-selector: css-value;
invalid-css is here!
As for what I mean with crudely, all that I find necessary to check is the presence of a : and a ; with text, and possibly a - in-between, it is not necessary to check if the css-selector itself actually exists as a CSS attribute nor if the CSS-value is a valid value of said selector.
Is there a way to ensure the entire input value MUST be true?
As a final note, if you see a potential danger not directly related to inserting script-tags or styling potential whole-page elements that I should be vary of, please let me know
Edit: due to many saying that I can't validate real CSS, I am going to specify my requirement a bit further; first, valid regex:
css-selector: css-value;
other-css-selector: other-css-value;
invalid regex:
css-selector: css-value;
invalid-css is here!
Secondly, what I want is something that validates if I can pass the string to:
$(element).css(validated-string);
And have chrome handle whether what is applied is actually valid, much like it does if you edit CSS live
Secondly, I mention PHP validation, but what I want is to update the CSS live so the user can see the effect of their edits as they add them
As regex you can use ^([A-Za-z\-]+?:\s*?[0-9A-Za-z\-%]+?;\s*?)*?$, but still i'm not quite sure that it will discard all the invalid css.
If you have test: 100something; is valid for the regex but is not valid CSS.

How to get filter conditions dropdown next to textbox when filterrow is enabled in jqxGrid?

I got a column with filter type textbox and i got filterrow enabled but i need the filter conditions dropdown to also appear next to the textbox because i need to be able to apply multiple conditions like not equal and other filters.
It seems like it is possible, but only by making changes to the jqxgrid.filter module, which the licensing seems to allow. I base this answer on the code for jQWidgets v3.4.0. (Of course, it's convenient to de-minify the code first.)
There are switch statements in several functions which switch on the filtertype (such as number and textbox). You can define your own filtertype that shows a textbox with a dropdown list by choosing a new name and adding case statements to fall through to the number case in the function definitions _updatefilterrowui, clearfilterrow, and refreshfilterrow. For the function _addfilterwidget, you need to add your own case and copy the code for the number case, but replace the line saying
var A = F._getfiltersbytype("number");
with
var A = F._getfiltersbytype("string");
to populate the dropdown list with the string comparison operators – or you can define your own filtertype, but this of course requires additional adjustments. In the function _applyfilterfromfilterrow you also need to add a case based on the code for the number case, with some adjustments. Basically, what seems to do the trick is to firstly remove the part about the decimal separator and secondly to not typecast the input string by changing
y = k.createfilter(d, new Number(p), w, null, u.cellsformat, C.gridlocalization);
to
y = k.createfilter(d, p, w, null, u.cellsformat, C.gridlocalization);
Note that this answer is possibly not complete, as I haven't done extensive testing (but I am interested to know of any problems, as I am looking for the same functionality as BeyondProgramming).

jQuery validation, NOT the normal plugin

I've been looking at the jQuery Validation Plugin and it seems like overkill (my site's script requirements are ballooning), and also not quite what I want.
Let me define some terminology: an <input type="text"> field's status is VALID if it matches both RegEx 1 and RegEx 2, PARTIAL if it matches RegEx 1 but not RegEx 2, and INVALID if it doesn't match RegEx 1.
For example, RegEx 1 could be /^[A-Z_]*$/ and RegEx 2 could be /^[A-Z]+(_[A-Z]+)*$/.
The requirements are:
any key press which would lead to an INVALID status is ignored, without interfering with focus or the caret position, and without the value ever being seen to change,
otherwise the status is updated after every key press to be either VALID or PARTIAL, and
whenever an input's status changes, a callback is invoked.
Seems pretty straightforward. This is basically the QStringValidator model.
I have jQuery core but I'm new to it. How can I implement this? Thanks.
P.S. if the best solution lies outside of jQuery, IE support is not required.
if (this.value.match(this.getAttribute('data-regex1')) {
if (this.value.match(this.getAttribute('data-regex2')) {
do_whatever_for_full();
} else {
do_whatever_for_partial();
}
} else {
do_whatever_for_invalid();
}
Put your regexes into the element as custom attributes (data-regex1, data-regex2) then check the data as it changes (not sure how many events you want to check but you probably have to check with onkeydown ignoring enter and tab, or you could create a timer onfocus and just check every half second or so).

Select class name (number) using RegEx & Jquery

I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.

transform pressed key values to english values

I have an input like this
<input id="guestCard" name="guestCard" onkeypress="transform(event)" type="text" value="" />
and I want to transform the key pressed on a keyboard regardless of which language settings to english character. E.g. when I press on czech keyboard + (with keycode 43) , I want to get 1 (with keycode 49).
Is there some standard way to do this? How would the function transform look like?
Alternatively I want the same functionality but using ajax (on asp.net mvc). Any ideas there?
Thanks in advance.
As far as I am aware, JavaScript is not locale aware - so you would need to somehow detect or have the user pick the appropriate transform mapping (in this case, perhaps a radio button for czech as the source and U.S. ASCII as the destination). Once that is taken care of, your function could be something like:
function transform(event) {
var code = (event.charCode) ? event.charCode : event.keyCode; // cross-browser happy
switch (code) {
case 43 : return "1";
}
}
There is a great test page to see how keyCode/charCode properties and the onKeyDown/Press/Up events behave in different browsers. http://asquare.net/javascript/tests/KeyCode.html
I doubt there is one but to create it, create an associative array, add some JS to a text field which saves the two values in the array and then press every key on the keyboard. After that, you can dump the array somewhere and use this as a constant in your code.
But be warned: Almost all users will have problems when they don't get the character on the screen which they've typed on the keyboard.
Trimack -
I think you are using the wrong event. You need onkeydown, and use the keyCode property of event.

Categories

Resources