jquery conversion for this javascript - javascript

I have the following code:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+document.getElementById('color').options[i].value;
text = document.getElementById('color').options[i].text.split(' - ');
}
This is part of the original code from javascript. I have successfully converted much of the other stuff into jquery but I can't seem to figure out how to convert this into jquery.
Please note that col is just value I am passing when calling the function which is usually "16"
Here is what I got so far:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+$('#color').val(i);
text = $('#color').val(i).text.split(' - ');
}
Also, the original code works fine in Chrome, Firefox, Opera and Safari but in IE (all version from 6 to 9) I get an error saying 'options[...].value' is not null or not an object
Thanks for the help!

You're mis-calling val.
Change it to $('#color option').eq(i).text() and $('#color option').eq(i).val()

$('#color option').each(function() {
var a = col + '|' + this.value,
b = this.text.split(' - ');
// do stuff with a and b
});

Related

Code works in code tester but not in adressbar

If i input my code here:
http://writecodeonline.com/javascript/
It works as intended, but if i input it in my adressbar with "javascript:" infront the alert box just shows the original string.
What is going wrong?
var string = "Sunshine & Whiskey";
var stringFeedback;
var i = 0;
string = string.replace("&","%26");
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
alert(string);
Edit:
If i input in my Chromium console it works fine, but if i make a bookmark with the same code it doesn't.
Any suggestions on how to fix that?
Try initialising i before the loop:
var i = 0;
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
Whatever, I recommend you use your browser console to test these code snippets.
You can use
encodeURIComponent("Sunshine & Whiskey");
That returns
Sunshine%20%26%20Whiskey
without any loop, it's a native method of javascript that is supported by all Browser.
MDN documentation

javascript - maxLength in IE8

Using a javascript function to prevent exceeding the length of a textfield, but to still allow pasting & editing within it. Needs to work in IE8 & Firefox.
$(function() {
var helper = document.createElement('textarea');
//if (!('maxLength' in helper)) {
var supportsInput = 'oninput' in helper,
ev = supportsInput ? 'input' : 'propertychange paste keyup',
handler = function() {
var maxlength = +$(this).attr('maxlength');
if (this.value.length > maxlength) {
this.value = this.value.substring(0, maxlength);
}
};
$('textarea[maxlength]').on(ev, supportsInput ? handler : function() {
var that = this;
setTimeout(function() {
handler.call(that);
}, 0);
});
//}
});
It works okay if the text is on one line (testing with maxLength = 25). However, it doesn't do carriage returns & line feeds or account for them properly.
For example, if I enter the following text on one line:
1111122222333334444455555
it uses all 25 characters.
However, if I enter text on each line & hit enter, this is what I am able to enter:
11111
22222
33333
4444
Which is only 22 characters. I know that it is detecting a carriage return, because when I put in:
11111
a character counter shows 5. When I hit the enter key, the counter goes to 6, if I enter 22222 the counter is now 11.
The code I'm using to count the characters is:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
I thought the issue might be some code I put in to resize the TextArea automatically, but it isn't. I'm sure I am just missing something on the code & would appreciate input on what I'm doing wrong & haven't seem to have figured out yet.
I stumbled upon the answer myself. It turns out the character counter I was using was not accurately counting the line breaks in the <textarea>.
Although I was using IE8, I found the answer in a question about Chrome counting characters wrong in textarea with maxLength attribute. That question is here.
The code I used before:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
has been modified to:
$("#myTextArea").keyup(function() {
var x = $("#myTextArea").val();
var newLines = x.match(/(\r\n|\n|\r)/g);
var addition = 0;
if (newLines != null) {
addition = newLines.length;
}
var j = x.length + addition;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
The embedded new lines must be transmitted as a CR LF pair - actually 2 characters. Thanks to the posters in the other thread for their help.

How to test if array item's text contains a substring?

I've been doing research on testing if a value exists in an array, and keep getting matches for indexOf('textvalue').
But, my 'textvalue' will be a substring, and therefore won't pull a match. This is because I'm passing the field name to the method, and just need to delete the "Door: Front Left;" text by matching the array item on "Door". Does anyone know how I can accomplish this?
Here's the example code I'm working on:
(spnSelectedDisclosures will have a list of selected fields, and this is the code to remove the previous field selection from the text, which is semi-colon delimited.)
var currentText = $("#spnSelectedDisclosures").text();
var existingArr = currentText.split(";")
for (i=0;i < existingArr.length;i++) {
var indexItem = " " + existingArr[i].toString(); // why is this still an object, instead of a string? Adding a space to it was a desperate try to make indexItem a string variable.
if (indexItem.contains(substringText)) { // offending line, saying the object has no method 'contains'
alert("there's been a match at: " + i);
textToRemoveIndex = i;
break;
}
}
var textToRemove = existingArr[textToRemoveIndex];
var newText = currentText.replace(textToRemove,"");
$("#spnSelectedDisclosures").text(newText);
What's about this?
for (i=0;i < existingArr.length;i++) {
if (existingArr[i].indexOf(substringText) > -1) {
alert("there's been a match at: " + i);
textToRemoveIndex = i;
break;
}
}
String.contains() has very limited support:
Browser compatibility
Chrome Not supported
Firefox (Gecko) 19.0 (19)
Internet Explorer Not supported
Opera Not supported
Safari Not supported
You need to use a regular expression or indexOf.
if (indexItem.indexOf(substringText)!==-1) {

How to read line by line of a text area HTML tag

I have a text area where each line contains Integer value like follows
1234
4321
123445
I want to check if the user has really enetered valid values and not some funny values like follows
1234,
987l;
For that I need to read line by line of text area and validate that.
How can i read line by line of a text area using javascript?
Try this.
var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
//code here using lines[i] which will give you each line
}
This works without needing jQuery:
var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
Two options: no JQuery required, or JQuery version
No JQuery (or anything else required)
var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
JQuery version
var lines = $('#myTextAreaId').val().split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
Side note, if you prefer forEach a sample loop is
lines.forEach(function(line) {
console.log('Line is ' + line)
})
This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.
var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
if (parseInt($(this) != 'NaN')
lines[] = parseInt($(this));
}
A simple regex should be efficent to check your textarea:
/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
A simplifyied Function could be like this:
function fetch (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}
for the html code below (as an example only):
<textarea id="targetted_textarea" rows="6" cols="60">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="fetch('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>

Javascript RegExp does not work in IE

The parameter return_value contains
<textarea>{"id":43,"description":"","item_id":28,"callback":"addNewAttachment","filename":"foo.jpg",,"type":"posts","ext":"jpg","size":145}</textarea>
The next code removes the textarea tags in Firefox, Chrome, so the content can be accessed in arr[1]. In IE alert("Failure") is called.
function addAttachment(returned_value) {
var re = new RegExp ("<textarea>(.+)</textarea>");
var arr = re.exec(returned_value);
if(arr != null && arr.length > 1) {
var json = eval('(' + arr[1] +')');
} else {
alert("Failure");
}
window[json.callback](json);
}
returned_value comes from an ajax call. I use JQuery.
TEST
This does not work either:
var re = new RegExp (/<textarea>(.+)<\/textarea>/);
SOLUTION
The problem was that IE was getting the textarea String uppercased while firefox was getting it lowercase.
The next regular expression solves it.
var re = new RegExp ('<textarea>(.+)</textarea)>','i');
Is this a case-sensitive issue? new RegExp(..., "i") might help?
Try using a regex literal:
var r = /<textarea>(.+)<\/textarea>/i;
What IE version do you use? I tested the following code in IE 7 and it worked:
<script>
var x = '<textarea>{"id":43,"description":"","item_id":28,"callback":"addNewAttachment","filename":"foo.jpg",,"type":"posts","ext":"jpg","size":145}</textarea>'
var r = new RegExp('<textarea>(.+)</textarea>');
var a = r.exec(x);
for (var i=1; i<a.length; i++)
alert(a[i]);
</script>
Edit: I checked with this code in IE7 and it also works. test.xml is a file that contains the string and sits in the folder next to the HTML page with the script. I assume it should also work with a dynamic page that returns the same thing.
<script>
function test(x) {
var r = new RegExp("<textarea>(.+)</textarea>");
var a = r.exec(x);
for (var i=1; i<a.length; i++)
alert(a[i]);
}
var rq = new XMLHttpRequest();
rq.open("GET", "test.xml", false);
rq.send(null);
test(rq.responseText)
</script>

Categories