I am using clone to generate dynamic HTML on click of button ,
following is my HTML for the same.
<input id="AddPhoneType" onclick="setEmailValues()" value="Gen Email" type="button">
<div style="margin-top: 10px;" class="ExtAddEmailTemplate" id="ExtAddEmailTemplate">
<input name="RemoveEmail" class="RemovePhoneBtn" value="-" id="RemoveEmail" type="button">
<input type="text" name="txtExtEmail" class="ExtEmailClass" value="" placeholder="Email" /></div>
<div id="EmailContainer"> </div>
And following is the script
$(document).ready(function () {
$('#AddExtEmail').click(function () {
$('<div/>', {
'class': 'ExtAddEmail', html: GetHtmlForEmail()
}).hide().appendTo('#EmailContainer').slideDown('slow');
});
});
function setEmailValues() {
$('<div/>', {
'class': 'ExtAddEmail', html: GetHtmlForEmail()
}).hide().appendTo('#EmailContainer').slideDown('slow');
}
function GetHtmlForEmail()
{
var len = $('.ExtAddEmail').length;
var emailValue = 'oner#one.com,twor#two.com';
var emaiArray = emailValue.split(",");
var $html = $('.ExtAddEmailTemplate').clone();
$html.find('[name=txtExtEmail]')[0].name = "txtExtEmail" + len;
return $html.html();
}
Now on click of button I need to generate 2 text box let say with respective email ID let say "oner#one.com", "twor#two.com"
Now my issue is that I am not able to set the value while generating the HTML
I have tried following
$html.find('[type=text]')[0].val('oner#one.com');
Have try finding using class , text etc. but was not able to set the value.
I also need to set value of dropdown , assuming that if I may able to set value of text box, will able to it do for dropdown also.
I am able to do it after HTML getting generated
$('#EmailContainer .ExtEmailClass').each(function () {
this.value = 'oner#one.com';
});
But I think if we can set value while generating HTML is most appropriate solution.
Thanks
You can use the below code it is working perfectly,
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Tring Reset</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input id="AddPhoneType" onclick="setEmailValues()" value="Gen Email" type="button">
<div style="margin-top: 10px;" class="ExtAddEmailTemplate" id="ExtAddEmailTemplate">
<input name="RemoveEmail" class="RemovePhoneBtn" value="-" id="RemoveEmail" type="button">
<input type="text" name="txtExtEmail" class="ExtEmailClass" placeholder="Email" /></div>
<input type="button" id="AddExtEmail" value="+"/>
<div id="EmailContainer"> </div>
<script>
$(document).ready(function () {
$('#AddExtEmail').click(function () {
$('<div/>', {
'class': 'ExtAddEmail', html: GetHtmlForEmail()
}).hide().appendTo('#EmailContainer').slideDown('slow');
});
});
function setEmailValues() {
$('<div/>', {
'class': 'ExtAddEmail', html: GetHtmlForEmail()
}).hide().appendTo('#EmailContainer').slideDown('slow');
}
function GetHtmlForEmail()
{
var len = $('.ExtAddEmail').length;
var emailValue = 'oner#one.com,twor#two.com';
var emaiArray = emailValue.split(",");
var $tryiy = $('.ExtAddEmailTemplate').clone();
$tryiy.find('[name=txtExtEmail]')[0].name = "txtExtEmail" + len;
$tryiy.find('[name=txtExtEmail'+len+']').attr("value",emaiArray[0]);
return $tryiy.html();
}
</script>
</body>
</html>
I have set the value using the attr("value",emaiArray[0]); property of the element using jquery and it is working fine
Related
Here is what is needed to do:
<input type="text" id="main" placeholder="Put URL Here">
Every time the User Presses enter (or a Button on side of screen) I need Jquery to create:
<input type="hidden" id="url_1" readonly value='<-- input value from main-->'>
<!-- user adds another to #main -->
<input type="hidden" id="url_2" readonly value='<-- input value from main-->'>
<!-- etc -->
Here is what I got So far (only using HTML)
<figure class="mb-4">
<input type="text" name="" id="" placeholder="Image URL">
<button id="addimage">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
For the Upload Image button, It submits a Image to my PHP upload image, and just returns the URL to the image
This will append the hidden inputs to the end of your <form> tag. It also keeps an array of urls in case that's useful. For this snippet, it shows the array in a div.
let urls = [], limit = 2, main, addButton, resetButton
window.addEventListener('load', () => {
main = document.querySelector('#main'),
addButton = document.querySelector('[data-url-saver]'),
resetButton = document.querySelector('[data-url-reset]');
addButton.addEventListener('click', () => saveURL())
resetButton.addEventListener('click', () => reset())
})
const saveURL = () => {
let u = main.value;
urls.push(u);
let h = `<input type="hidden" data-url-hidden id="url_${urls.length}" readonly value=${u} />`
document.querySelector('form').insertAdjacentHTML('beforeend', h);
main.value = "";
let de = document.querySelector('#debug');
de.innerHTML = urls.join(", ");
if (urls.length >= limit) {
addButton.setAttribute('disabled', 'disabled');
main.setAttribute('disabled', 'disabled');
main.setAttribute('placeholder', 'Maximum URLs accepted')
}
}
const reset = () => {
urls = [];
document.querySelectorAll('[data-url-hidden]').forEach(e => e.parentNode.removeChild(e));
addButton.removeAttribute('disabled');
main.removeAttribute('disabled');
document.querySelector('#debug').innerHTML = "";
}
<form>
<input type="text" id="main" placeholder="Put URL Here">
<button data-url-saver type='button'>enter</button>
<button data-url-reset type='button'>reset</button>
</form>
<div id='debug'></div>
Create a div for hidden urls like
<div id="urls"></div>
try in jquery
var counter = 1;
$('#main').keypress(function (e) {
if(e.which== 13){ // enter key code
var url = $('#main').val();
$('#urls').append('<input type="hidden" id="url_'+ counter +'" readonly value="' + url + '" >');
$('#main').val(''); //clearing the input
counter++;
}
});
If you want to add ascending URL and if you have the link, then you can use the function below.
function addImage(){
var link = document.querySelector('#main').value;
var all_links = document.getElementById('all_urls');
if (link.length > 0){
code = `
<input type="hidden" id="url_${all_links.children.length}" value="${link}"/>
`
all_links.innerHTML += code;
console.log(document.getElementById('all_urls'))
}
}
<figure class="mb-4">
<input type="text" id="main" placeholder="Put URL Here">
<div id="all_urls">
<!--All the links are added here-->
</div>
<button id="addimage" onclick="addImage()">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
In jQuery
// Cache some elements
const div = $('div');
const main = $('#main');
$('button').click(() => {
// Grab the value
const val = main.val();
// Create the id based on the current
// number of inputs
const id = div.find('input').length + 1;
// Append the new input
div.append(`<input readonly id="url_${id}" value="${val}" />`);
// Reset the main input
main.val('');
});
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
And the equivalent in vanilla JS:
// Cache some elements
const div = document.querySelector('div');
const main = document.querySelector('#main');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false)
function handleClick() {
// Create the id based on the current
// number of inputs
const id = div.querySelectorAll('input').length + 1;
const html = `<input readonly id="url_${id}" value="${main.value}" />`;
// Append the new input
div.insertAdjacentHTML('beforeend', html);
// Reset the main input
main.value = '';
};
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
I try to add input dynamically. However each input I add is blank without a name.
$(document).ready(function() {
var moreUploadTag = '';
$('#attachMore').click(function() {
moreUploadTag += '<input type="text"/>';
jQuery(moreUploadTag).detach().appendTo("#boxed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="boxed">
<input type="text" name="" />
</div>
<p id="attachMore">attachMore</p>
The purpose I left it blank without a name is I want to crate the name dynamically:
$('#addName').click(function(){
//$('input').attr("name", $(this).attr("name") + "test");
var named = $('input').val();
$('input').attr("name", $('input').attr("name") + named);
});
$(document).ready(function() {
$('#attachMore').click(function() {
var moreUploadTag = '';
moreUploadTag += '<input type="text"/>';
jQuery(moreUploadTag).detach().appendTo("#boxed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxed">
<input type="text" name="" />
</div>
<p id="attachMore">attachMore</p>
<p id="addName">addName</p>
However it adds name to all input.
My question is how to add name input each of the inputs?
Thanks in advance for the help. Cheers.
Are you looking for something like this?
$('#addName').click(function(){
$('input').each(function(){
var input = $(this);
input.attr("name", input.val());
});
});
$(document).ready(function() {
$('#attachMore').click(function() {
var moreUploadTag = '';
moreUploadTag += '<input type="text"/>';
jQuery(moreUploadTag).detach().appendTo("#boxed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxed">
<input type="text" name="" />
</div>
<p id="attachMore">attachMore</p>
<p id="addName">addName</p>
I think the problem is you need to tell jquery what name goes with what input.
var inputHtml = '<div class="inputGroup"><input type="text" /><button class="addName">add name</button></div>';
var yourname = 'allen';
$('.body').on('click', '.addInput', function() {
$('.target').prepend(inputHtml);
});
$('.body').on('click', '.addName', function() {
if($(this).siblings('input').length) {
$(this).siblings('input').attr('name', yourname);
// debug
alert($(this).parent().children('input').attr('name'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="body">
<div class="target"></div>
<button class="addInput">add input</button>
</div>
So my dilemmna is that I don't know how to record what the user inputs. (my goal as of now is to simply print what the user enters in an input box, not to add the numbers)
var x = document.getElementById('textboxone').value;
Why isn't this working?
<!DOCTYPE html>
<html>
<head>
<link href="cssFiles/ttt.css" rel="stylesheet" type="text/css"></link>
<script Language ="JavaScript">
//create skeleton divs
function createDivs () {
var s;
s = '<div class="simplebox" id="divBody">Bla 3 bla</div>';
document.write(s);
}
//create body skeleton
function createBodyDivs (sID) {
var s;
s = '<div class="smallerbox" id="divInput">';
s += '<div id="textboxone"><span>Add <input type="text" ></input></span></div>';
s += '<div id="textboxtwo"><span>To <input type="text" ></input></span></div>';
s += '<div id= style="margin-top: 100px;"><span> Click here to find the answer! <input type="button" value = "Answer Generator" OnClick="(this.form)"></input></span></div>';
var oDiv = document.getElementById(sID);
oDiv.innerHTML = s;
}
//adding the two numbers from input boxes
function addnumbers(form){
var x = document.getElementById('textboxone').value;
alert(x)
}
</script>
</head>
<body>
<script Language ="JavaScript">
createDivs();
createBodyDivs('divBody');
</script>
</body>
</html>
Check out AngularJS my friend! :)
JSFIddle Demo
<div ng-app="">
<input type="text" ng-model="data.message" />
<h1>{{data.message}}</h1>
<div class="{{data.message}}"></div>
</div>
using: https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js
I've quickly checked the code and first of all you input button will not trigger addNumbers(form) since the onclick of the input doesn't point of that function.
Then for the function itself, document.getElementById('textboxone').value returns undefined because the actual value you want is in the <input> and not in the <div id="textboxone">
So if you have you're createBodyDivs function modified so that the id where on the input, then this document.getElementById('textboxone').value would actually return the correct value.
function createBodyDivs (sID) {
var s;
s = '<div class="smallerbox" id="divInput">';
s += '<div><span>Add <input type="text" id="textboxone" ></input></span></div>';
s += '<div><span>To <input type="text" id="textboxtwo" ></input></span></div>';
s += '<div id= style="margin-top: 100px;"><span> Click here to find the answer! <input type="button" value = "Answer Generator" OnClick="(this.form)"></input></span></div>';
var oDiv = document.getElementById(sID);
oDiv.innerHTML = s;
}
For the click binding, you button should be the following for it to work:
<input type="button" value = "Answer Generator" OnClick="addnumbers()"></input>
my intension is to send a hidden count value form view to controller in spring mvc,everything is working but iam not getting the count in the controller,plese do some favour
my view is
<HTML>
<HEAD>
<script type="text/javascript" src="resources/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var i = 1;
//var c = 0;
$("#AddSection").click(function() {
i++;
$("<div />").append($("<input />", {
type: "text",
name: "Section" + i
})).appendTo("#someContainer");
//c = i;
document.getElementsByName("Count").Value = i;
alert(i);
});
$("input").live("click", function() {
$("span").text("Section: " + this.name);
});
});
</SCRIPT>
</HEAD>
<BODY>
<form method="get" action="addProfile">
ProfileName<input type="text" name="pname"><br />
SectionName<input type="text" name="Section1">
<input type="button" id="AddSection" value="AddSection">
<div id="someContainer"></div>
<input type="hidden" id="hiddenSection" name="Count" />
<span></span> <input type="submit" value="save">
</form>
</BODY>
</HTML>
You have a typo:
document.getElementsByName("Count").Value = i;
// ^----Typo!
value is lowercase:
document.getElementsByName("Count")[0].value = i;
// ^----Fixed!
// ^-------- return HTML Collection, take first.
Better use id:
document.getElementById("hiddenSection").value = i;
You're using jQuery, so you can use one of the following:
$("#hiddenSection").val(i);
$('input[name="Count"]').val(i);
How can I do this through the tag itself?
Change type from text to password
<input type='text' name='pass' />
Is it possible to insert JavaScript code inside the input tag itself to change type='text' to type='password'?
Try:
<input id="hybrid" type="text" name="password" />
<script type="text/javascript">
document.getElementById('hybrid').type = 'password';
</script>
Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).
You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.
I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84
To work in Internet Explorer:
dynamically create a new element
copy the properties of the old element into the new element
set the type of the new element to the new type
replace the old element with the new element
The function below accomplishes the above tasks for you:
<script>
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
</script>
Yes, you can even change it by triggering an event
<input type='text' name='pass' onclick="(this.type='password')" />
<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">
Here is what I have for mine.
Essentially you are utilizing the onfocus and onblur commands in the <input> tag to trigger the appropriate JavaScript code. It could be as simple as:
<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>
An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:
<script type="text/javascript">
function password_set_attribute() {
if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" ||
document.getElementsByName[0].value == null) {
document.getElementsByName("login_text_password")[0].setAttribute('type','text')
document.getElementsByName("login_text_password")[0].value = 'Password';
}
else {
document.getElementsByName("login_text_password")[0].setAttribute('type','password')
}
}
</script>
Where HTML looks like:
<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>
let btn = document.querySelector('#btn');
let input = document.querySelector('#username');
btn.addEventListener('click',()=> {
if ( input.type === "password") {
input.type = "text"
} else {
input.type = "password"
}
})
<input type="password" id="username" >
<button id="btn">change Attr</button>
I had to add a '.value' to the end of Evert's code to get it working.
Also I combined it with a browser check so that the input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
document.getElementById("input_id").attributes["type"].value = "text";
This is a simple toggle with jQuery. It works also with the the ASP.NET MVC EditorFor() when you have a DataType.Password on the model property.
function showPassword() {
let password = $(".password");
if (password[0].type == "password") {
password[0].type = "";
}
else {
password[0].type = "password";
}
}
$(".show-pass").click(function (e) {
e.preventDefault();
var type = $("#signupform-password").attr('type');
switch (type) {
case 'password':
{
$("#signupform-password").attr('type', 'text');
return;
}
case 'text':
{
$("#signupform-password").attr('type', 'password');
return;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="password" class="show-pass">
This is not supported by some browsers (Internet Explorer if I recall), but it works in the rest:
document.getElementById("password-field").attributes["type"] = "password";
or
document.getElementById("password-field").attributes["type"] = "text";
You can try this:
const myTimeout = setTimeout(show, 5000);
function show() {
document.getElementById('pass').type = "text";
}
clearTimeout(myTimeout);
//html
<input type="password" id="password_input">
<i onclick="passwordDisplay()" class="ti-eye"></i>
//js
const input = document.getElementById("password_input")
function passwordDisplay() {
if (input.attributes["type"].value == "text")
input.attributes["type"].value = "password"
else
input.attributes["type"].value = "text"
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
document.getElementById("password-field".focus();
}
</script>
</head>
<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />
</body>
</html>