I cannot see where I am going wrong with this. My code is...
function firstC()
{
var x = document.getElementsByClassName("uValue");
for(var i = 0; i < x.length; i++) {
x.value.charAt(0).toUpperCase();
}
}
It is called by...
<td><input type="text" name="firstname" value="(required)" id="firstName" class="uValue" onclick="empty(this.id)" onblur="firstC()" /></td>
The empty() function works correctly by removing the value of the input box if its value is "(required)", but I cannot get the firstC() function to capitalise the first character of any input.
EDIT: I am using getElementsByClassName as there are multiple input boxes which I am trying to allow to use the same function.
You forgot to assign the value back
function firstC()
{
var x = document.getElementsByClassName("uValue");
for(var i = 0; i < x.length; i++) {
x[i].value = x[i].value.charAt(0).toUpperCase() + x[i].value.substr(1);
}
}
You should instead pass the this into your inline JS eventers:
onclick="empty(this)" onblur="firstC(this)"
Example
function empty(el) { // el now refers to the this referrer
el.value="";
}
function firstC(el) {
var val = el.value;
el.value = val.charAt(0).toUpperCase() + val.substr(1);
}
<input type="text" onclick="empty(this)" onblur="firstC(this)" value="(required)" id="firstName" class="uValue" name="firstname">
P.S: don't forget that instead of using empty() and value="(required)" you can simply use the placeholder attribute
placeholder="(required)"
Related
I want to add space after every 3rd number, but this code doesn't work if the input is type="number". Does someone know how to modify the code to make it work even for type="number"
? Here is my input:
<input type="number" id="phone" autocomplete="off" placeholder="(+420)">
And also here is the script:
<script>
document.getElementById('phone').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{3})/g, '$1 ').trim();
});
</script>
Try this:
function insertBlankAfterEveryThreeCharacters(str) {
var str=str.split(" ").join("").split("");
var formatted=[];
while(str.length) {
for(var i=0; i<3 && str.length; i++) {
formatted.push(str.shift());
}
if(str.length) formatted.push(" ");
}
return formatted.join("");
}
Use in your event:
this.value=insertBlankAfterEveryThreeCharacters(this.value);
document.getElementById('phone').addEventListener('input', function (e) {
this.value=insertBlankAfterEveryThreeCharacters(this.value);
});
function insertBlankAfterEveryThreeCharacters(str) {
var str=str.split(" ").join("").split("");
var formatted=[];
while(str.length) {
for(var i=0; i<3 && str.length; i++) {
formatted.push(str.shift());
}
if(str.length) formatted.push(" ");
}
return formatted.join("");
}
<input id="phone">
<input type="number"... makes it so you can go up/down one = I assume not an intended result...
Your place holder has parentheses and a plus in it - It is not what you seem to be wanting in the solution...
I have a object named MYMODCLASS that contains all my module functions. One of these functions addNumberValues(id, getId) loops through a collection of number inputs using the getElementsByName method and adds the values to check that the values are less than 100.
When I invoke the function using the following notation:
window.onload = document.getElementsByName('grade').oninput = MYMODCLASS.addNumberValues('info', 'grade');
The function only fires once when the document loaded, but not again.
When I invoke it as a parameter to an input element is works consistently:
<input type="number" value=0 id="ind" name="grade" min="0" max="100" oninput="MYMODCLASS.addNumberValues('info', 'grade')" required>
<input type="number" value=0 id="nv" name="grade" min="0" max="100" oninput="MYMODCLASS.addNumberValues('info', 'grade')" required>
The problem with the latter invocation is that I have to repeat the oninput parameter 30 times. Therefore, I want to use the former invocation for the ``addNumberValues function.
MYMODCLASS.addNumberValues = function (id, getId) {
var element = document.getElementById(id);
var el = document.getElementsByName(getId);
var i = 0;
el.forEach((ite) => {
console.log(ite.value);
if (!isNaN(parseFloat(ite.value)) && isFinite(ite.value)) {
if (i === 0) {
i = parseFloat(ite.value);
} else {
i = parseFloat(i) + parseFloat(ite.value);
}
}
})
console.log(i);
if (i > 100 || i < 0) {
element.className = 'lbwarn';
element.innerText = i;
alert("Grade exceeds 100!")
} else {
element.className = 'lbinfo';
element.innerText = i;
}
};
Edit
So after reading the comments I decided to create a loop that sets the function for each individual element by id. But this is still not working.
window.onload = function() {
var numel = document.getElementsByName('grade');
numel.forEach((p) => {
console.log(p.id);
document.getElementById(p.id).oninput = MYMODCLASS.addNumberValues('info', 'grade');
})
}
How can I get the invocation to work consistently using my last method?
I want to create a html form, it have 2 group(Name and fruit), each group have two check boxes, When user clicks the checkbox that input name are user_checkbox[] and fruit_checkbox[] , its will do something,i need to use array and for loop to get the user which group of checkboxes was checked , but it seems not to allow me use multiple for loop.
My Html File
//group1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showinputtext();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showinputtext();" >Billy
//group2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showinputtext();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showinputtext();" >Banana
My Javascript file
function showinputtext() {
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var n = 0; n < name.length; n++) && for (var f = 0; f < fruit.length; f++) {
if(name[n].checked && fruit[f].checked){
dosomething..................
}
}
but it is not work for me, any idea?? thx
Try nested for loops.
function showinputtext(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
};
if you use jquery
try it :
Example
$("[type='checkbox']").on("click",function(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
});
Why not use forEach? Looks a bit nicer and does the same job in this instance:
function showInputText() {
var nameCheckboxes = document.getElementsByName("user_checkbox[]");
var fruitCheckboxes = document.getElementsByName("fruit_checkbox[]");
nameCheckboxes.forEach(function(nameCheckbox) {
fruitCheckboxes.forEach(function(fruitCheckbox) {
if (nameCheckbox.checked && fruitCheckbox.checked) {
alert ("ok");
};
});
});
I renamed the variables and the function to make this a bit more readable!
Just remember to change the function calls in the onclick attributes if you go for this approach:
// Group 1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showInputText();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showInputText();" >Billy
// Group 2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showInputText();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showInputText();" >Banana
However, reading your post, you might not need to do this at all. It seems unnecessary to iterate through both groups in a nested loop. Why not instead add each item to an array and "Do stuff" with both when the form is submitted?
I would change your checkboxes to have a fruit-input and user-input class:
<input type="checkbox" name="peter" class="user-input">
<input type="checkbox" name="banana" class="fruit-input">
Then I would add an event listener to the fruit-input and user-input elements which listen for changes to the checkboxes. When a change event occurs it then checks if the input has been checked or not, and it will then add or remove from either the selectedFruits or selectedUsers arrays:
document.getElementsByClassName("fruit-input")
.forEach(function(input){
input.addEventListener("change", selectFruit);
});
document.getElementsByClassName("user-input")
.forEach(function(input){
input.addEventListener("change", selectUser);
});
var selectedFruits = [];
var selectedUsers = [];
function selectFruit() {
var fruit = this.getAttribute("name");
if (this.checked) {
selectedFuits.push(fruit);
} else {
selectedFruits.remove(fruit);
}
}
function selectUser() {
var user = this.getAttribute("name");
if (this.checked) {
selectedUsers.push(user);
} else {
selectedUsers.remove(user);
}
}
Notice how the functions grab the value to add to the arrays from the input element's name attribute. Your current name attributes are invalid as they should really be unique.
It is even possible to refactor my suggestion above to have one generic input field listener and determine the array to add to based on a data attribute or something. But this is a good starting point.
After all this you can do whatever you need with the selectedFruits or selectedUsers arrays.
Try placing the second for loop inside the first one, like so
for (var n = 0; n < name.length; n++) {
for (var f = 0; f < fruit.length; f++) {
if(chboxsEng_single[n].checked && chboxsEng_fruit[f].checked){
dosomething..................
}
}
}
Be aware that this will go through every single value of f a total of n times, which may or may not be behaviour that you desire, it's not clear in the question.
in my process text filed in array i need to get the value via javascript but my code is not working my code following
<input type="text" id="itemid[]" name="itemid[]" class="span12"/>
and javascript code is
function getstock()
{
var itemidarr=document.getElementById('itemid[]');
if(itemidarr!= null)
{
alert(itemidarr.length);
}
}
any other solution for this
The IDs can't contain brackets, these: [], so:
<input type="text" id="itemid1" name="itemname1" class="span12"/>
<input type="text" id="itemid2" name="itemname1" class="span12"/>
<input type="text" id="itemid3" name="itemname1" class="span12"/>
Then you have to loop through the IDs:
function getstock()
{
for(var i=1; i<=3; i++){
var itemidarr=document.getElementById("itemid"+i);
if(itemidarr!= null) alert(itemidarr.length);
}
}
The id attribute here cannot contain [ ].
Put your textboxex in "fieldset tag"
Like:
<fieldset id="field">
//Put you text boxes here<input type='text'>
</fieldset>
Access these by:
document.getElementById("list....").getElementsByTagName("input")[indexoftext];
indexoftext is the text box you wan to choose.
Hope it helps!
you can try something like this below
<input type="text" id="itemid" name="itemid" class="span12"/>
function getstock()
{
var itemidarr = document.getElementsByName('itemid');
for(var i = 0; i < itemidarr.length; i++){
var item=document.getElementsByName('itemid')[i].value;
if(item!= null)
{
alert(item);
}
}
}
You can't make an array to fill in an input text, only for input like radio or checkbox.
Text input only accept a single string.
function getstock() {
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
can u use this code
i got the result
function getstock1()
{
alert("test");
var itemidarr = document.getElementsByName('itemid[]');
for (var i = 0; i < itemidarr.length; i++)
{
alert(itemidarr[i].value);
}
How is repeated code HTML for five times?
like repeated(echo) a input <input type="text" name="ok"> with a js code five times.
I mean this is that, a input by a js code echo five times
I want after run jQuery code output is this (5 input):
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
how is it?
Your question isn't totally clear, do you mean this?
for (var i = 0; i<5;i++) {
$("body").append("<input type='text' name='ok'>");
}
function EchoInput(html, count) {
var result = [];
for (var i = 0; i < count; i++)
result.push(html);
return result.join("");
}
To use this function, you could do something like this:
document.write(EchoInput("<input type='text' name='ok'>", 5));
var body = $('body');
for(var i = 0; i < 5; i++) {
body.append('<input type="text" name="ok">');
}
http://jsfiddle.net/ucbsh/1/
Instead of creating HTML, you can create elements directly.
Here is a way that let you set different names on each input field. Right now all five have the name "ok", but you can change that in the array:
// use ready event so that the page is loaded:
$(document).ready(function(){
// decide where to add the elements:
var container = $('body');
// loop over an array of names:
$.each(['ok','ok','ok','ok','ok'], function(idx, name) {
// create an element and add to the container:
container.append($('<input/>', { type: "text", name: name }));
});
});