How to check if input name is inside an array in Jquery? - javascript

I want to know how I can check if input name is equal to name inside an array.
I have multiple inputs like below code:
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
And I have an array Like this:
var array = ['last_name', 'email'];
I want to add class to div, that wrap the input his name inside the array.
I don't want to use 2 loops.

You can use the following code:
var inputs = $("input");
var array = ['last_name', 'email'];
inputs.each(function(){
if(array.indexOf($(this).attr("name")) >= 0){
alert($(this).attr("name")+" exists");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
The HTML to the code is same as used by you in your question, I have added a bit of JQuery, that is simple to understand.
I hope it was helpful.

check output in browser console:
$(document).ready(function() {
var array = ['last_name', 'email', 'dsfdsfds'];
array.forEach(function(element) {
var x = document.getElementsByName(element);
console.log(x);
});
});
//check output in browser console
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>

there is your solution :)
$(document).ready(function() {
var array = ['last_name', 'email'];
var inputs = $("div[class='inputMain']").find("input");
array.forEach(function(name) {
inputs.each(function (x){
if (inputs[x].name === name) {
inputs[x].parentNode.classList.add("myClass")
}
});
});
console.log(inputs.prevObject);
});
https://jsfiddle.net/12es37ko/62/
you can check result into browser console :)

Related

Multiple input events vanilla JS

Struggling to get all my input fields to work as intended.
The first field is working as it should but i want the phone input to change the phone_field to change as well.
How do i go around making this work with multiple fields?
<div class="formBox">
<label for="full_name">Fullt navn</label>
<input name="name" type="text" id="fullname" />
</div>
<div class="formBox">
<label for="phone">Tlf:</label>
<input name="phone" type="text" id="phone" />
</div>
<div class="formBox">
<label for="email">Epost:</label>
<input name="email" type="text" id="email" />
</div>
<div>
<h3 id="full_name_field">Ola Normann</h3>
</div>
<p id="phone_field">+47 123 12 123</p>
const input = document.querySelector('input');
const name = document.getElementById('full_name_field');
input.addEventListener('input', updateValue);
function updateValue(e) {
name.textContent = e.target.value;
}
You could have a function that updates phone_field and fires when a key is pressed in phone:
HTML:
<input name="phone" type="text" id="phone" onkeydown="updatePhoneField"/>
JS:
function updatePhoneField() {
phoneVal = document.getElementById("phone").value;
document.getElementById("phone_field").innerHTML = phoneVal;
}
Found a solution that works ( for now ) probably not ideal and not the best way to do it but!
const input1 = document.getElementById("fullname");
const output1 = document.getElementById("full_name_field");
document.getElementById('fullname').onkeyup = function () {
"use strict";
document.getElementById('full_name_field').textContent = this.value}

HTML Form Validation Logic in JavaScript or jQuery

I have a form for which I should write validation logic.
Let's say there's an input field like this.
<div class="group1"><label>Product code</label> <input id="code" name=""code" type="text" class="control1"></div>
If I want to make it a required field how do I write the logic?
I don't have access to the CSS files. But there's an input like this which I can use which has a red outline.
<div class="group1 row has-error">
<div><input type="text" class="control1"></div>
</div>
I have to give the code in JavaScript or jQuery.
Get an element and set true on required property.
const input1 = document.getElementById('code');
input1.required = true;
const input2 = document.querySelector('div.group1>div>input.control1');
input2.required = true;
<form>
<div class="group1"><label>Product code</label>
<input id="code" name="code" type="text" class="control1">
</div>
<div class="group1 row has-error">
<div>
<input type="text" class="control1">
</div>
</div>
<input type="submit">
</form>
I think this is what you need
$("#formSubmit").submit(function(e) {
e.preventDefault();
var error_text = "<div class='text-danger error_val'>Cannot be empty</div>"
var data = $("#formSubmit").serializeArray();
var allInputs = $("#formSubmit input");
for(var i=0; i<data.length; i++){
if(data[i].value.length == 0){
$(".group1").addClass('has-error');
var errorDiv = $(allInputs)[i].closest('.has-error');
$(error_text).insertAfter( errorDiv );
}
}
});
.has-error input{
border: 1px solid #f00;
}
.text-danger{
color:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formSubmit">
<div class="group1 row">
<label>Product code</label>
<input id="code" name="code" type="text" class="control1" >
</div>
<button type="submit" id="submitButton">Save</button>
</form>
I know it`s too late but you can use these functions to make an input required/optional
function makeFieldRequired(element, elementName) {
let jqueryObj = $(element);
jqueryObj.attr('title', `${elementName} is required`);
jqueryObj.attr('required', 'true');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function makeFieldOptional(element) {
let jqueryObj = $(element);
jqueryObj.removeAttr('required');
jqueryObj.removeAttr('title');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function refreshFormValidtion(form) {
$(form).removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Combine two textbox value into other textbox in lowercase with dash

I have two text type inputs. I want to convert them into one textbox(Lowercase with dash) while typing just like below.
<input type="text" name="first">
<input type="text" name="last">
I want combine this two text box into another textbox
Example: Nikhil Patel to nikhil-patel
I am trying to combine below inputs but can't.
function conv(){
var title, author;
title = document.getElementById("title").value;
author = document.getElementById("author").value;
/*converting to LowerCase*/
title = String.toLowerCase(title);
author = String.toLowerCase(author);
var out = title + "-" + author;
document.getElementById("output").value = output;
}
<div class="form-group">
<label>Title :</label>
<input class="form-control" type="text" name="title" id="title" />
</div>
<div class="form-group">
<label>Author :</label>
<input class="form-control" type="text" name="author" id="author" />
</div>
<div class="form-group">
<label>Output :</label>
<input class="form-control" type="text" name="output" id="output"/>
</div>
Output is not printing automatically
Try This if you want like this...
var input = $('[name="first"],[name="last"]'),
input1 = $('[name="first"]'),
input2 = $('[name="last"]'),
input3 = $('[name="final"]');
input.change(function () {
input3.val(input1.val() + ' - ' + input2.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="first" id="1" value="">
<input type="text" name="last" id="2" value="">
<input type="text" name="final" id="3" value="" readonly>
<HTML>
<HEAD>
<SCRIPT>
function conv(){
var first, second;
first = document.getElementById("first").value;
second = document.getElementById("second").value;
/*converting to LowerCase*/
first = String.toLowerCase(first);
second = String.toLowerCase(second);
var out = first + "-" + second;
document.getElementById("out").value = out;
}
</SCRIPT>
</HEAD>
<BODY>
<input type="text" name = "first" id="first" onkeyup = 'conv()'/>
<input type="text" name = "second" id ="second" onkeyup = 'conv()'/>
<input type="text" name = "out" id="out"/>
</BODY>
</HTML>
this is just a sample with 3 text boxes where
first two boxes will be for input
and third will auto populate using the javascript
I hope it'll help you. All is did was to add extra id's.

Computing using functions and arrays / Output error: Not a Number

Background: I'm practicing arrays and functions and am having trouble computing the sum of array items. I'm pretty sure there is something wrong with the function I'm writing but I'm not sure what. Using 8 input fields I'm pulling data into a array one item at a time and converted to floating numbers(for now...I'll try to fix that later). I've created a function that will compute the total of this list but it only outputs NaN.
Any suggestions are highly appreciated!
function myfunction() {
list = [];
list[0] = parseFloat(document.getElementById('number1').value);
list[1] = parseFloat(document.getElementById('number2').value);
list[2] = parseFloat(document.getElementById('number3').value);
list[3] = parseFloat(document.getElementById('number4').value);
list[4] = parseFloat(document.getElementById('number5').value);
list[5] = parseFloat(document.getElementById('number6').value);
list[6] = parseFloat(document.getElementById('number7').value);
list[7] = parseFloat(document.getElementById('number8').value);
function total(myvals) {
let total = 0;
for (let i = 0; i <= myvals.length; i++) {
total += myvals[i];
}
return total;
}
document.getElementById('results').innerHTML = total(list);
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
<input type="submit" value="Compute Score" onclick="javascript:myfunction()">
</form>
<div id="results"></div>
Here is a simple example using a for loop with querySelectorAll.
Additionally, I cleaned up your code a bit. Run the snippet below:
EDIT: Included some comments to show what's happening.
function myfunction() {
let total = 0;
//get the value for each element being called by querySelectorAll
//add values to total to get a sum
document.querySelectorAll('input').forEach(el => total += +el.value);
//append the new value to the results div
document.querySelector('#results').innerHTML = total;
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
</form>
<br/><br/>
<button type="submit" onclick="myfunction()">Compute Score</button>
<br/><br/>
<div id="results"></div>
This is resolved. I was able to fix my source code by removing
"<=" in the for loop and adding "<" in its place. Thanks everyone, I will look over everything else for extra practice!
1 - in HTML forms and their elements use names.
2 - each element of a form can be accessed by name with the form as parent
3 - if several elements have the same name (with the same type of preference) then they form an object collection
PS: I have used here [... myForm.numX] to transform the myForm.numX collection to array, so that it can accept the arry.map () method
this way:
const myForm = document.forms['my-form']
, res = document.getElementById('results')
;
myForm.onsubmit = evt =>
{
evt.preventDefault() // disable submit
let list = [...myForm.numX].map(inp => parseFloat(inp.value))
res.textContent = list.reduce((t,v)=>t+v,0)
// control...
console.clear()
console.log( myForm.numX.length, JSON.stringify(list) )
}
<form name="my-form">
<input type="text" name="numX" placeholder="num 1"><br>
<input type="text" name="numX" placeholder="num 2"><br>
<input type="text" name="numX" placeholder="num 3"><br>
<input type="text" name="numX" placeholder="num 4"><br>
<input type="text" name="numX" placeholder="num 5"><br>
<input type="text" name="numX" placeholder="num 6"><br>
<input type="text" name="numX" placeholder="num 7"><br>
<input type="text" name="numX" placeholder="num 8"><br>
<button type="submit">Compute Score</button>
</form>
<div id="results">..</div>

HTML Form Values don't push to JavaScript array

Ok, so I am trying to push the value of an HTML form input to a JavaScript array. When I load the page and submit values through the form, it returns empty strings in the array. I don't understand why this is happening. Thank you for your help.
Relevant HTML:
<form>
<div class="form-group">
<label for="name1">Name: </label>
<input type="text" class="form-control b" id="nameone">
<label for="pref1">Preferences: </label>
<input type="text" class="form-control a" id="prefone"> </div>
<div class="form-group">
<label for="name2">Name: </label>
<input type="text" class="form-control c" id="nametwo">
<label for="pref2">Preferences: </label>
<input type="text" class="form-control a" id="preftwo"> </div>
<div class="form-group">
<label for="name3">Name: </label>
<input type="text" class="form-control d" id="namethree">
<label for="pref3">Preferences: </label>
<input type="text" class="form-control a" id="prefthree"> </div>
<div class="form-group">
<label for="name4">Name: </label>
<input type="text" class="form-control e" id="namefour">
<label for="pref4">Preferences: </label>
<input type="text" class="form-control a" id="preffour"> </div>
<!-- ... -->
<button type="submit" class="btn btn-primary" id="sbm">Submit</button>
</form>
Relevant JavaScript:
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
// ...
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
document.getElementById('sbm').onclick = namesdefine();seat(document.getElementsByClassName('a').value);check();changeHTML();
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
You're calling the namesdefine() function when you assign to .onclick. You should be assigning the function to .onclick, so leave out the () after it.
document.getElementById('sbm').onclick = namesdefine;
Either use:
document.getElementById('sbm').onclick = namesdefine;
Or
document.getElementById('sbm').addEventListener('click', namesdefine);
If you need to call them all, use this:
document.getElementById('sbm').onclick = function () {
namesdefine();
seat(document.getElementsByClassName('a').value);
check();
changeHTML();
}
And it's always a good practice to check for null after getElementById()
Try to get your data in a loop.
You can use getElementByTagName or getElementByClassName.
var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
//Create array here arr.push(elements[i].value);
}
You can call that in your click function.
Hope that helps.

Categories