How to pass ID as argument in JavaScript function? - javascript

HTML body:
<div id = "id1">
<input type="text" class="name">
<input type="button" onclick="myFunction(id1)" value="Click me">
</div>
<div id = "id2">
<input type="text" class="name">
<input type="button" onclick="myFunction(id2)" value="Click me">
</div>
JavaScript:
function myFunction(param)
{
var content = document.getElementById("param");
var x = content.getElementByClassName("name").value;
alert(x);
}
I want to use passed ID in the JavaScript function to get more values.

Pass the id parameters in to the onclick events as strings. Then give each text input a class of name, not an id (ids have to be unique to a single element). Finally, use the id param to find the container element using getElementById, and use querySelector to drill down to the text input.
function myFunction(param)
{
let el = document.getElementById(param)
let name = el.querySelector('input.name').value
console.log(name)
}
<div id = "id1">
<input type="text" class="name">
<input type="button" onclick="myFunction('id1')" value="Click me">
</div>
<div id = "id2">
<input type="text" class="name">
<input type="button" onclick="myFunction('id2')" value="Click me">
</div>

function myFunction(param)
{
var content = document.getElementById(param.id);
var x = content.getElementsByClassName("name")[0].value;
alert(x);
}
<div id = "id1">
<input type="text" class="name" id="name">
<input type="button" onclick="myFunction(id1)" value="Click me">
</div>
<div id = "id2">
<input type="text" class="name" id="name1">
<input type="button" onclick="myFunction(id2)" value="Click me">
</div>
here is the above working snippet of your question.
check the above changes here I used param.id instead of only param
also, your using the class selector so class selector gives response in array format so I had used getElementsByClassName("name")[0].value.

You can use querySelector to get the input value having type text
function myFunction(param)
{
var content = document.getElementById(param);
alert(content.querySelector('input[type="text"]').value);
}
<div id = "id1">
<input type="text" class="name">
<input type="button" onclick="myFunction('id1')" value="Click me">
</div>
<div id = "id2">
<input type="text" class="name">
<input type="button" onclick="myFunction('id2')" value="Click me">
</div>

function myFunction(btn){
const [input] = btn.parentElement.children;
console.log('input value: ' + input.value);
}
<div id = "id1">
<input type="text" class="name">
<input type="button" onclick="myFunction(this)" value="Click me">
</div>
<div id = "id2">
<input type="text" class="name">
<input type="button" onclick="myFunction(this)" value="Click me">
</div>

You can do something like below. i have kept id of text box different. And the ID is passed to the function from HTML. This is one of the approaches to get the value from the text-box.
Update: Used class on name text box. And fetch values for the element with class value of 'name'.
<div id = "id1">
<input type="text" class="name">
<input type="button" onclick="myFunction('id1')" value="Click me">
</div>
<div id = "id2">
<input type="text" class="name">
<input type="button" onclick="myFunction('id2')" value="Click me">
</div>
function myFunction(param) {
const divElement = document.getElementById(param);
const txt = divElement.getElementsByClassName('name')[0].value
console.log(txt);
}
JS fiddle: https://jsfiddle.net/sagarag05/Lm7fn6dx/10/
Let me know if this works.

Related

How to Manipulate the Text element in Html by A Variable whose value is given by the user?

I am trying to Manipulate the Text with id 'varname' (Spartans) with the value inputted in the form saved as a variable 'input'
<div class="middle">
<h2 class="greet" id="demo">Welcome Back, <span id="varname">Spartan</span></h2>
<div class="form">
<form>
<label for="Name">Enter Your Name</label>
<input type="text" id="Name">
<input type="submit" value="Submit" onclick="myFunction()">
</form>
</div>
<script>
function myFunction(){
var input= document.getElementById("Name").value;
document.getElementById("varname").innerHTML = input;
}
</script>
Use <input type="button"> instead of <input type="submit">
https://jsfiddle.net/yt0kgnqe/
In your form, try this:
<form id="manipulate">
<label for="Name">Enter Your Name</label>
<input type="text" id="Name">
<input type="submit" value="Submit">
</form>
In your javascript,
document.getElementById("manipulate").addEventListener("submit", e => {
e.preventDefault()
const formData = new FormData(e.target)
document.getElementById('varname').innerHTML = formData.get("Name")
})
e.preventDefault() stops the form from reloading the page and formData gets the input values inside the form

How to get HTML cloned form values

I'm trying to get the values from my form when the user clones the row. When I clone the rows are the id still the same? If so how do I make the new rows to have a unique id?
jQuery(function($) {
var $button = $('#add-row'),
$row = $('.period-row').clone();
$button.click(function() {
$row.clone().insertBefore($button);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="heading">Please select appointment period</h3>
<div class="form-wrapper">
<form action="#" id="date-form" name="date-form" method="POST">
<div class="period-row">
<label for="start">From:</label>
<input type="datetime-local" name="start[]" id="start">
<label for="end">To:</label>
<input type="datetime-local" name="end[]" id="end">
</div>
<input type="button" id="add-row" name="add-row" value="add period" />
<button type="submit">submit</button>
</form>
</div>
I don't understand what exactly you want and to do it on the proper way you have to use class on the input and not id because the id is unique. But I hope this code will help you.
jQuery(function($) {
var $button = $('#add-row'),
$row = $('.period-row').clone();
$button.click(function() {
let from = $('#start').val();
let to = $('#end').val();
$row.clone().insertBefore($button).addClass('active');
$('.period-row.active').find("#start").val(from);
$('.period-row.active').find("#end").val(from);
$('.period-row').removeClass('active');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="heading">Please select appointment period</h3>
<div class="form-wrapper">
<form action="#" id="date-form" name="date-form" method="POST">
<div class="period-row">
<label for="start">From:</label>
<input type="datetime-local" name="start[]" id="start">
<label for="end">To:</label>
<input type="datetime-local" name="end[]" id="end">
</div>
<input type="button" id="add-row" name="add-row" value="add period" />
<button type="submit">submit</button>
</form>
</div>

Cloning an item with js and the increment sign (++), my error with double increment i

Here's my problem:
document.addEventListener("DOMContentLoaded",function() {
const adduser = document.querySelector("#add-user");
const original = document.querySelectorAll('#input');
let i = 0;
function duplicate() {
let clone = original[0].cloneNode(true);
clone.id = "input" + ++i;
clone.name = "input" + ++i;
original[0].after(clone);
}
adduser.onclick = function() {
duplicate();
};
});
<form action="second.php" method="post">
<div class="form-group">
<label for="username">Name of the user:</label>
<input type="text" class="form-control multinput" class="username" id="input" placeholder="Enter the user's name" name="fullName">
<button type="button" class="btn btn-default" id="add-user">+ Add a user</button>
</div>
<div class="buttons">
<input type="submit" name="submit" id="submit" class="button" value="Submit"/>
</div>
</form>
As you've already guessed, I'm trying to clone a field, but I want to increment two properties of this very field (in this case, that's an input field).
Now my problem is that, as soon as I push the button to clone the INPUT, in this case, I will increment both the id and the name, but unfortunately, they won't stay the same number, in fact the markup will become:
<form action="second.php" method="post">
<div class="form-group">
<label for="username">Name of the user:</label>
<input type="text" class="form-control multinput" id="input" placeholder="Enter the user's name" name="fullName">
<input type="text" class="form-control multinput" id="input" placeholder="Enter the user's name" name="input3">
<input type="text" class="form-control multinput" id="input" placeholder="Enter the user's name" name="input1">
<button type="button" class="btn btn-default" id="add-user">+ Add a user</button>
</div>
<div class="buttons">
<input type="submit" name="submit" id="submit" class="button" value="Submit">
</div>
</form>
this one. As you can notice, we have two wrong actions, in my option, which are:
The input cloned and then attached to the original input have the wrong order because is added to the very first element (0) so the last element attached won't be ascendant, but in this case, it will have the higher number.
Both the id and the name will be incremented, so I will have the same input with the id=1 and the name=2, which is not ideal.
Any hint on how to fix the problem?
Increment i only once, before you assign the new id and name. Also, use insertAdjacentElement on the button to insert each new input before it, rather than after, to insert the new input:
function duplicate() {
i++;
let clone = original[0].cloneNode(true);
clone.id = "input" + i;
clone.name = "input" + i;
document.querySelector('button').insertAdjacentElement('beforebegin', clone);
}
document.addEventListener("DOMContentLoaded", function() {
const adduser = document.querySelector("#add-user");
const original = document.querySelectorAll('#input');
let i = 0;
function duplicate() {
i++;
let clone = original[0].cloneNode(true);
clone.id = "input" + i;
clone.name = "input" + i;
document.querySelector('button').insertAdjacentElement('beforebegin', clone);
}
adduser.onclick = duplicate
});
<form action="second.php" method="post">
<div class="form-group">
<label for="username">Name of the user:</label>
<input type="text" class="form-control multinput" class="username" id="input" placeholder="Enter the user's name" name="fullName">
<button type="button" class="btn btn-default" id="add-user">+ Add a user</button>
</div>
<div class="buttons">
<!-- <input type="button" name="next" value="submit"> -->
<input type="submit" name="submit" id="submit" class="button" value="Submit" />
</div>
</form>
Three things:
Increment i after using it, not each time you need it or it will incremented multiple times instead of 1 every duplication
use setAttribute
append to the parent element, not after the original input to achieve descending order
document.addEventListener("DOMContentLoaded",function() {
const adduser = document.querySelector("#add-user");
const original = document.getElementById('input');
let i = 1;
function duplicate() {
let clone = original.cloneNode(true);
clone.setAttribute("id", "input"+i);
clone.setAttribute("name", "input"+i);
i++
original.parentNode.appendChild(clone);
}
adduser.onclick = function() {
duplicate();
};
});
<form action="second.php" method="post">
<div class="form-group">
<label for="username">Name of the user:</label>
<input type="text" class="form-control multinput" class="username" id="input" placeholder="Enter the user's name" name="fullName">
<button type="button" class="btn btn-default" id="add-user">+ Add a user</button>
</div>
<div class="buttons">
<input type="submit" name="submit" id="submit" class="button" value="Submit"/>
</div>
</form>

How to show up the div on button click which is not actually set to none in html?

Im trying it with laravel. On button click I need to display the same div .
My code:
<h6>Other features </h6>
<div id="add1">
<input type="text" name="selprice" />
<input type="submit" value="+" id="add">
</div>
This is my html code.Here,when I click the button**(ie.,+)** it should show up the same div(ie add1).
Script code:
<script type="text/javascript">
$(document).ready(function () {
$("#add").click(function () {
$("#add1").show();
});
});
</script>
This is what I have tried.
if you are cloning div use class instead of id.
use this context to get the click element
use append to add the cloned div to container
$(document).ready(function() {
$(document).on("click",".add",function() {
$("#container").append($(this).parent(".add1").clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=container>
<div class="add1">
<h6>Other features </h6>
<input type="text" name="selprice" />
<input type="submit" value="+" class="add">
</div>
</div>
Update
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type="submit" value="+" class="add"></div>';
$("#container").append(clone);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=container>
<div class="add1">
<h6>Other features </h6>
<input type="text" name="selprice" />
<input type="submit" value="+" class="add">
</div>
</div>
Here you go with the solution https://jsfiddle.net/nuu4ofwu/2/
var cnt = 1;
$(document).on('click', 'input[type=submit]', function(){
cnt++;
var div = $(this).parent().clone();
$('body').append(div);
$('div:last-child').attr('id', 'add' + cnt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="add1">
<h6>Other features </h6>
<input type="text" name="selprice" />
<input type="submit" value="+" id="add" />
</div>
You should define another div as a template:
HTML:
<div id="template" style="display:none;">
<div id="add_2">
<h6>Other features</h6>
<input type="text" name="selprice" />
<input type="submit" value="+" id="add_button_number"></div>
</div>
</div>
Javascript:
<script>
$('#add').click(function(){
var str = $('#add_2').html();
$('#add1').after(str);
})
</script>

JavaScript how to send different entities but keeping the same id?

Suppose I have 2 areas separated by div containers, I need to send the Id values from the different areas, locally when the function is called in that container.
extract:
<script>
document.getElementById('compare_name").innerHTML = "Changed";
</script>
<div class = "details>
<span id="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
<div class = "details">
<span id="compare_name">no2</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
You cannot use same ID for more than one element. you can use name instead like below:
<script>
var x = document.getElementsByName("compare_name");
for(var i = 0; i < x.length ; i++){
x[i].innerHTML = "Changed";
}
</script>
<div class = "details>
<span id="compare_name" name="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
<div class = "details">
<span id="compare_name" name="compare_name">no2</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
As others indicates that, to follow the rule, the ID attribute should not be duplicated, but it doesn't matter if you don't rely on it.
I guess the asker might only need to change one text inside the div which is clicked, not all the spans, so just a little change.
<html>
<head>
<title>Test</title>
<script>
function add_compare(el) {
var divChildEles = el.parentNode.parentNode.childNodes;
for (var i=0; i<divChildEles.length; i++) {
if (divChildEles[i].nodeType==1 && divChildEles[i].nodeName=="SPAN") {
//console.log(divChildEles[i].innerText);
divChildEles[i].innerText='changed';
}
}
}
</script>
</head>
<body>
<div class = "details">
<span id="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare(this)">
</form>
</div>
<div class = "details">
<span id="compare_name">no2</span>
<form id="view-details1">
<input type="button" value="Add to Compare" onclick="add_compare(this)">
</form>
</div>
</body>
</html>
id in JavaScript must be unique. instead, you can give them a class with the same name
<script>
var x=document.getElementByClassName('compare_name");
for(var i=0;i<x.lengh;i++)
x[i].innerHTML = "Changed"
</script>
<div class = "details>
<span class="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
<div class = "details">
<span class="compare_name">no2</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>

Categories

Resources