How to set input field maxlength from label - javascript

I'm trying to figure out a way to change the maxlength of ajax called input fields by pulling the value to set out of the field's label and updating the default value. The field labels all follow the same format - id, class, type and maxlength. The new maxlength value to set is always present in the id ...max_X_characters...
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029" class="gwt-
TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
So in this example I need to set the maxlength to 4.
The other problem is that there are multiple input fields, often with different maxlength values. See here for an example.
I was thinking of setting a script to pull out the value once the fields have loaded, but I don't mind admitting it, this one's over my head - hopefully one of you bright guys n gals can figure it out!
Update: Thanks for the suggestions, I've tried both, in various combinations, but can't get them to work.
Here's the code suggested by Ecwid's tech team that sets all input fields on the page to one maxlength (6 in this case)
`Ecwid.OnPageLoaded.add(function(page){if (page.type == "PRODUCT") {
$("input.ecwid-productBrowser-details-optionTextField").attr('maxlength','6');
};
})`
However, as I stated there are input fields with different maxlengths for some products.
I've tried replacing the '6' above with a function, based on your suggestions, to get the maxlength from the input id, but can't get it to work.
Any more ideas?
Thanks
Update:
Cracked it (nearly), here's the working code
`Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});`
Thanks so much for your help, it works like a dream on the product page but there is another area where it doesn't. A customer can edit the input text via a pop-up, from the shopping basket.
The fields have similar code:
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029"
class="gwt-TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
Suggestions very welcome
Chris
UPDATE:
Many, many, many thanks to ExpertSystem (you genius you!) - I think we've got it. (tested on IE10, firefox 21, chrome 27).
The code below is for people using Yola and Ecwid together, but I guess the original code may work for people using other sitebuilders. It limits the number of characters a user can enter into input fields, in Ecwid, by checking for a number in the input field's title (in this case the value between 'max' and 'characters') and replacing that as the field's maxLength value. It limits fields in the product browser, in the html widgets and in the cart pop-up.
Here it is:
Go to Yola's Custom Site Tracking Code section. In the 'Footer Code' column (actually placed at the bottom of the 'body'), place this code:
<script>
Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});
</script>
<script>
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
};
</script>
and this into the 'Header Code' column:
<script>
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
</script>
That's it! You're good to go.

It is not exactly clear what is meant by "ajax called input fields", but supposing that the input fields are created and added to DOM inside a success callback for some AJAX call, you can place the following piece of code in your pages <head>:
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
}
And then, at the end of the AJAX call's "onSuccess" callback, append this:
fixMaxLength(document);
UPDATE:
Based on your comments below, if you need to apply fixMaxLength() to div's of class "popupContent", which get dynamically added to your DOM, an easy way (not the most efficient though) would be adding a listener for DOM modification events (e.g. somewhere in <head>):
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
(NOTE: I have only tested it on latest versions of Chrome and Firefox, so I am not really sure for which other/older browsers this does work.)
(NOTE2: GGGS, has tested it (and found it working) on IE10 as well.)

How about a regular expression on your id attribute? Such as the following:
jQuery('input').each(function() {
var idVal = jQuery(this).attr('id');
var regex = /max_(\d+)_characters/g;
var result = regex.exec(idVal);
var length = result[1];
});
This is a loop over all the inputs. Once this is run, the length variable will have the proper length each go through, for your next step.

Related

Issues in setting cookies for store form input values in javascript

I took below code from online,
var myValues = [];
for(i=0;i<inputs.length;i++) {
validateEmail(inputs[i]);
myValues.push(inputs[i].value);
}
// Save them fot later use
localStorage.myValues = JSON.stringify(myValues);
// After clicking the button you can retrieve them back
var oldValues = JSON.parse(localStorage.myValues);
I created simple asp page,
Now, If i click the next after after enter some input value, it will go to next page, and again i click back, it doesn't show entered input values.
I need to show that values, may i know, how can i achieve this one thanks in advance.
Here is the worked jsfiddle
I need to add with my existing javascript code for achieving my need.
But i just confused, how to add code?
Can anyone help me? Thanks in advance.
On page load, you must add the following code:
var $inputs = $(".input");
var myValues = localStorage.getItem("myValues") ? JSON.parse( localStorage.getItem("myValues") ) : [];
for(var i = 0; i < myValues.length; i++) {
$inputs[i].value = myValues[i];
}
This will make sure that on page load, if any data is present in the localStorage it will be populated in the respective input fields.
Now when you click on next button:
$("#nextbutton").click(function () {
var myValues = [],
$inputs = $('.input');
for (i = 0; i < $inputs.length; i++) validateEmail($inputs[i]);
if ($('.invalid').length !== 0) return false;
for (i = 0; i < $inputs.length; i++) {
myValues.push($inputs[i].value)
}
localStorage.myValues = JSON.stringify(myValues);
});
This is used to store the data into the localStorage after validation.

Possibility to select specific input fields javascript

I will show you guys what I got with jsfiddles because it makes it easier to explain.
This is what kind of form setup im running right now. (Just showing you some fields, not all)
http://jsfiddle.net/XK99Z/2/
When you change the number in one of the input fields the price will immediately change too.
It uses this piece of JS for that:
function changeTotalFromCount(input) {
var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
var count = input.value;
var price = unitPrice * count;
var formattedPrice = '\u20ac ' + price.toFixed(2);
var label = input.parentNode.nextElementSibling;
label.innerHTML = '';
label.appendChild(document.createTextNode(formattedPrice));
}
When they press the submit button they will be taken to another page where the order is with their personal details, a print button and a change order button. If they press the change order button they will go back to the page like this:
http://jsfiddle.net/KPfUT/
And as you can see the price won't show next to the number anymore, but someone helped me find a solution for this problem:
function initTotals() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
changeTotalFromCount(inputs[i]);
}
}
window.onload = initTotals;
http://jsfiddle.net/7LKf7/2/
Now there is one problem, it won't work together with other input fields, like name, phone number, adres, etc.
http://jsfiddle.net/Af724/1/
I was hoping someone could help me find a solution to this maybe let JS know i only want it to run for input type="number" since all the personal details input fields are text.
I'm nowhere near experienced in JS so please let me know if you don't understand my question or you need some more information, thanks in advance!
Use document.querySelectorAll() to only select the type="number" input elements:
var numberInputs = document.querySelectorAll('input[type="number"]');
for (var i = 0; i < numberInputs.length; i++) {
changeTotalFromCount(numberInputs[i]);
}
or check the elements for their type:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute('type') == 'number')
changeTotalFromCount(inputs[i]);
}

How to get all radio buttons inside a table?

i have group of radio buttons inside a table along with other inputs in this table, and i can't get the radio buttons by id or name or by tag name, i want to get them by type if this possible, because id and name is auto generated by JSF, and i don't want to change this.
so the requirement is: get all radio buttons only (not all inputs) inside the table so i can loop on them.
I hope there's only one set of radio buttons. In that case something like this can help:
var inputs = yourForm.elements;
var radioes = [];
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radioes.push(input[i]);
}
}​
In case there are more than one set of radio buttons, better approach would be to have a dictionary with the name as the key and the value as the array of radio buttons in the group.
I know the question doesn't mention jQuery, but I just wanted to demonstrate the simplicity of it; please consider this more of a selling point of "hey, look how nice jQuery is".
// look how pretty I am
var radioButtons = $('table#MyTableId input[type="radio"]');
Given your form name is yourForm ... (<form name = "yourForm">) ... an easy way is just to parse all form elements and check for the type, something like this:
var your_namespace = {};
your_namespace.your_function = function() {
var l = document.yourForm.elements.length;
for (i=0; i<l; i++) {
var type = yourForm.elements[i].type;
if (type=="radio") alert("Form element " + i + " is a radio!");
}
}
Instead of alerting you can ofc do alot of other things with the element id.
You can have this way easier when using a framework like MooTools or JQuery.

JavaScript: get custom button's text value

I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))

javascript dropdown to change all dropdown in table

I have a requirement of changing all dropdown values in all the rows in a tale based on master dropdown. say someone selects "value 2" in dropdown1, dropdown2 values in all the rows in the table should show "value2".
function change(){
var cid = document.frm.locdropdown.selectedIndex;
document.frm.locdropdown2.selectedIndex = cid;
}
is the java script I use to change it but this changes only first row.
please help..
From your example code it looks like you've given the same ID to all your locdropdown2 elements? Maybe you should post an example of your table HTML. It's normal practice to give unique IDs to elements, so you may want to test the NAME attribute instead, but anyway something like the following should work:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var inputs = document.getElementsByTagName("input");
for (var i=0, l = inputs.length; i < l; i++) {
if (inputs[i].id == "locdropdown2")
inputs[i].selectedIndex = cid;
}
}
Another option is to loop through each row in the table. The following example assumes your locdropdown2 inputs are the only thing in the third column, but you can adapt to suit your actual layout:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var tableRows = document.getElementById("yourTableId").tBodies[0].rows;
for (var i=0, l=tableRows.length; i < l; i++) {
tableRows[i].cells[2].firstChild.selectedIndex = cid;
}
}
Note: I haven't actually tested any of that code, but it should be more than enough to get you started and you can tweak as needed. (You can use Google to learn about tBodies, rows, cells, firstChild, etc.)

Categories