textarea isn't reading input that I have made [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">

Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">

Related

Unable to retain the table values after refreshing the browser window

Created a form using html, javascript. After entering the fields, when i click submit button, it saves the user data in localstorage and updates the table rows dynamically. But once i refresh the browser, the table holding the information of all users is lost. I want to retain the table after refreshing the browser.
Click here to view screenshot of page Before refresh
Click here to view screenshot of page After refresh
JS Code :
var testObject = [];
var users = {};
function clear(){
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username,usermail,password,location,organization,gender){
if(username!="" && usermail!="" && password!="" && location!="" && organization!="" && gender!=""){
return true;
}
}
function removeDivChild(str)
{
if(document.getElementById(str).querySelector('p')){
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val,cdiv)
{
if(val=="" && document.getElementById(cdiv).querySelector('p')==null)
{
var node = document.createElement("P");
if(document.getElementById(cdiv).className=="textbox"){
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
}
else if(document.getElementById(cdiv).className=="radiobox"){
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if(val!="" && document.getElementById(cdiv).querySelector('p')!=null)
{
document.getElementById(cdiv).lastElementChild.remove();
}
}
function save(){
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if(document.getElementById("m").checked){
genval = document.getElementById("m").value;
}
if(document.getElementById("f").checked)
{
genval = document.getElementById("f").value;
}
if(IsValid(userval,eval,passval,locval,orgval,genval))
{
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
updateTable();
}
else
{
appendToDiv(userval,"userdiv");
appendToDiv(eval,"maildiv");
appendToDiv(passval,"passdiv");
appendToDiv(locval,"locdiv");
appendToDiv(orgval,"orgdiv");
appendToDiv(genval,"gendiv");
}
}
function updateTable(){
localStorage.setItem("user", JSON.stringify(testObject));
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
if(i==0){
var nodeh = document.createElement("tr");
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
nodeh.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
nodeh.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
nodeh.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
nodeh.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
nodeh.appendChild(onode);
var gnode = document.createElement("th");
var gtext = document.createTextNode("gender");
gnode.appendChild(gtext);
nodeh.appendChild(gnode);
document.getElementById("t").appendChild(nodeh);
}
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
var nodeg = document.createElement("td");
var textg = document.createTextNode(usr[i].gender);
nodeg.appendChild(textg);
noder.appendChild(nodeg);
document.getElementById("t").appendChild(noder);
clear();
}
HTML code :
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="check.js"></script>
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male"/> Male
<input type="radio" name="gender" id="f" value="female"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
After the back and forth in the comments on your question I decided to just create an example from your code sample. Most of it was untouched however I did add comments to the things that I did change.
// I moved the declaration of the testObject below to let the functions be created first
// so i can use teh new loadFromStorage function to create the object
var users = {};
// This is a new function I created
function loadFromStorage() {
// parse the 'user' object in local storage, if its empty return an empty array
return JSON.parse(localStorage.getItem('user')) || [];
}
function clear() {
// I didn't touch this function
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username, usermail, password, location, organization, gender) {
// I didn't touch this function
if (username != "" && usermail != "" && password != "" && location != "" && organization != "" && gender != "") {
return true;
}
}
function removeDivChild(str) {
// I didn't touch this function
if (document.getElementById(str).querySelector('p')) {
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val, cdiv) {
// I didn't touch this function
if (val == "" && document.getElementById(cdiv).querySelector('p') == null) {
var node = document.createElement("P");
if (document.getElementById(cdiv).className == "textbox") {
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
} else if (document.getElementById(cdiv).className == "radiobox") {
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if (val != "" && document.getElementById(cdiv).querySelector('p') != null) {
document.getElementById(cdiv).lastElementChild.remove();
}
}
// Changes in this function
function save() {
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if (document.getElementById("m").checked) {
genval = document.getElementById("m").value;
}
if (document.getElementById("f").checked) {
genval = document.getElementById("f").value;
}
if (IsValid(userval, eval, passval, locval, orgval, genval)) {
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
// Saving testObject to the persistent storage here because this is where it belongs
localStorage.setItem("user", JSON.stringify(testObject));
updateTable();
} else {
appendToDiv(userval, "userdiv");
appendToDiv(eval, "maildiv");
appendToDiv(passval, "passdiv");
appendToDiv(locval, "locdiv");
appendToDiv(orgval, "orgdiv");
appendToDiv(genval, "gendiv");
}
}
// Changes in this function
function updateTable() {
// pulled out the saving and the loading of user from localStorage here,
// everything should already be saved or loaded by the time we call
// this function.
// Also re-wrote this function because it was messy and hard to read, always remember you write code for humans not computers so slightly longer variable names that are descriptive are really good.
// get a reference to the table
var tbl = document.getElementById('t');
// remove all the child rows, except for the header
// CSS Selector explained:
// #t - find the table by the id (you used t)
// > tr > td - find all td's that are direct children of the t table
Array.prototype.forEach.call(document.querySelectorAll('#t > tr > td'), function(node) {
node.parentNode.removeChild( node );
})
// loop over all the 'users' in 'testObject'
for(var i = 0; i < testObject.length; i++){
// store a reference to the current object to make the code easier to read
var currentObject = testObject[i];
// create the TR
var tr = document.createElement('tr');
// Create the td's
var tdUserName = document.createElement('td');
var tdEmail = document.createElement('td');
var tdPassword = document.createElement('td');
var tdLocation = document.createElement('td');
var tdOrganization = document.createElement('td');
var tdGender = document.createElement('td');
// create the text nodes
var userName = document.createTextNode(currentObject.uname);
var email = document.createTextNode(currentObject.email);
var password = document.createTextNode(currentObject.pass);
var location = document.createTextNode(currentObject.loc);
var organization = document.createTextNode(currentObject.org);
var gender = document.createTextNode(currentObject.gender);
// add the elements to their containers
tdUserName.appendChild(userName);
tdEmail.appendChild(email);
tdPassword.appendChild(password);
tdLocation.appendChild(location);
tdOrganization.appendChild(organization);
tdGender.appendChild(gender);
// add the td's to the row
tr.appendChild(tdUserName);
tr.appendChild(tdEmail);
tr.appendChild(tdPassword);
tr.appendChild(tdLocation);
tr.appendChild(tdOrganization);
tr.appendChild(tdGender);
// add the row to the table
tbl.appendChild(tr);
}
// call your clear function
clear();
}
// load the object from storage
var testObject = loadFromStorage();
// populate the table
updateTable();
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male" /> Male
<input type="radio" name="gender" id="f" value="female" /> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<!-- Added the header to the table, it isn't removed now when rebuilding it -->
<table id="t" border="1">
<thead>
<tr>
<td>Username</td>
<td>Email</td>
<td>Password</td>
<td>Location</td>
<td>Organization</td>
<td>Gender</td>
</tr>
</thead>
</table>
Here is a link to a JSFiddle because this example wont run properly because it accesses localStorage but is sandboxed. Working Example

How to apply a class attribute to an HTML string (not rendered on the document)

I am am developing code for am automator to improve the project with several pages.
I have a textarea input where I can enter HTML and it shows me the HTML with the right structure.
HTML:
<textarea name="message">
<input type="text" value="TextTwo" id="texttwo"/>
<input type="text" value="DataOne" id="dataone"/>
<input type="text" value="NumberTwo" id="numbertwo"/>
<input type="text" value="TextOne" id="textone"/>
<input type="text" value="DataTwo" id="datatwo"/>
<input type="text" value="NumberOne" id="numberone"/>
</textarea>
<button>process</button>
JS/JQuery:
$('button').click(function () {
var code = $('textarea[name=message]').val();
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(code);
});
I would like to apply classes following these rules:
The input that has the word "Text" value in applying the class = "text"
The input that has the word "Data" value in applying the class = "data"
The input that has the word "Number" value in applying the class = "number"
An example of how the code would output in textarea
<input type="text" value="TextTwo" id="texttwo" class="text" />
<input type="text" value="DataOne" id="dataone" class="data" />
<input type="text" value="NumberTwo" id="numbertwo" class="number" />
<input type="text" value="TextOne" id="textone" class="text"/>
<input type="text" value="DataTwo" id="datatwo" class="data" />
<input type="text" value="NumberOne" id="numberone" class="number" />
DEMO CODE
What is a good approach to do this using JQuery?
I updated your fiddle and had this code working -- Can't give you a link since I don't actually have a fiddle account:
$('button').click(function () {
var code = $('textarea[name=message]').val();
// The best thing to do here is to turn that string of HTML into
// DOM elements and let the browser do the work.
var elms = jQuery.parseHTML(code);
var result = "";
// Now that we've processed the HTML into an array, work with it.
for (var i = 0; i < elms.length; i++) {
var el = elms[i];
if (el.tagName && el.tagName.toLowerCase() === "input") {
// Great! We we have an 'input' element.
var val = el.value;
if (val.indexOf("Text") !== -1) {
el.className = "text";
}
if (val.indexOf("Data") !== -1) {
el.className = "data";
}
if (val.indexOf("Number") !== -1) {
el.className = "number";
}
}
if (el.nodeType === 3) {
// Handle text nodes
result += el.nodeValue;
} else {
result += el.outerHTML;
}
}
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(result);
});
Under the assumption that all the html in the textarea is valid, What we can do is just build the html into a div and then format the html with jQuery. After this is done just get the content and put it in the textarea.
$('button').click(function () {
var code = $('textarea[name=message]').val(),
$code = $('<div />').html(code),
classes = {'Text': 'text', 'Data': 'data', 'Number': 'number'};
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('input', $code).each(function(){
var t = this,
$t = $(this);
for(key in classes){
if(t.value.indexOf(key) > -1){
$t.addClass(classes[key]);
return;
}
}
});
$('#output').val($code.html());
});
http://jsfiddle.net/LC5y3/4/
DEMO
$('button').click(function () {
var code = $.parseHTML($('textarea[name=message]').val());
console.log(code);
var newCode = "";
code = $.grep(code, function (n, i) {
if (n.nodeValue) {
return n.nodeValue.trim()
} else {
return (n.outerHTML && n.outerHTML.trim())
}
});
for (var i = 0; i < code.length; i++) {
var element=$(code[i]);
element.addClass(element.attr("type"));
newCode += code[i].outerHTML;
}
console.log(newCode);
console.log(code);
if (!$('#output').length) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(newCode);
});
You can use the attribute contains selector.
jsFiddle
$('input[id*="text"]').addClass('text');
$('input[id*="number"]').addClass('number');
$('input[id*="data"]').addClass('data');
You can dynamically build the elements:
$('input').addClass('className').attr('value','number');

Javascript to alert a user that the same info has already been entered

First I should say I am a javascript newbie so forgive my ignorance.
I'm creating a form that has three functions and also uses array:
Add - To accept a name (if field left blank it should ask the user to enter a name in an alert box)
Find - To verify a name has not already been entered (in an alert box)
List - To list the names that have been entered (in an alert box)
I have the list function working (good). The alert to enter a name comes up after you enter a name as well as when you leave the field blank (not good)
and I can't get the find function to work at all.
My code is below and I've tried so many iterations and searched so many sites for help, also tried firebug; I'm hoping someone can point me in the right direction.
Untitled
<body>
<script type="text/javascript">
var a = new Array();
function list() {
var s = "";
for (i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add() {
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
if (myTextField.value == "") {
alert("Please enter a name");
return false;
}
function find() {
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField) {
alert("Sorry, the name " + a[i] + " already exists. Try again");
}
}
}
</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
You have done it almost, but some lil errors.. here you can check it jsfiddle
HTML:
<input type="text" id="myText" /><br>
<input type="button" value="Add a name" class="add_button"/>
<input type="button" value="List the names" class="list_button"/>
<input type="button" value="Find" class="find_button"/>
JS:
$(".add_button").live("click", function(){
add()
});
$(".list_button").live("click", function(){
list()
});
$(".find_button").live("click", function(){
find()
});
var a = new Array();
function list()
{
var s = "";
for(i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
if (myTextField.value == "")
{
alert ("Please enter a name");
return false;
}
myTextField.value = "";
}
function find()
{
//If the name already exists you should get a warning
var status = true;
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
{
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
status = false;
break;
}
}
if(status==true)
{
a[a.length] = myTextField.value;
}
myTextField.value = "";
}
The code had a couple of errors, here's a working version: http://jsfiddle.net/sAq2m/2/
html:
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="listItems()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
js:
var a = [];
function listItems()
{
var s = "";
for(var i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
return false;
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
var v = myTextField.value
if (!v){
v = prompt("You have not entered a name, please enter one.");
}
a.push(v);
console.log(a);
myTextField.value = "";
return false;
}
function find()
{
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
return;
}
}

JavaScript hiding plain text similar to password

I am trying to hide/show the plain text of a hashing function, I have been able to hide the input field but i have not been able to hide/show the plain text, the webpage has a input field and under that is the text that i am typing, then there is the hashed text, i am trying to replace the plain text with bullets.
I tried hiding it by counting the number of characters in the field and then repeating the bullet that many times. but now the page does not function at all.
<!DOCTYPE html>
<html>
<body>
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input
size="80"
input type="text"
rows="7"
id="edValue"
type="text"
onKeyPress="edValueKeyPress()
"onKeyUp="edValueKeyPress()">
<p id="string">Original text: </p>
<p id="lblValue">The SHA256 hash is: </p>
<script type="text/javascript" src="sha256.js">
</script>
<script type="text/javascript">
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The SHA256 hash is: "+sha256_digest(s);
var TheText = document.getElementById("string");
TheText.innerText = "Original text: "+s;
}
function toggleType() {
var obj = document.getElementById('edValue');
if (obj.type == 'password') {
obj.type = 'text';
} else {
obj.type = 'password';
repeat();
}
}
function repeat() {
var length = this.value.length;
var count = document.getElementById("edValue");
String.prototype.repeat = function(n) {
return new Array(1 + n).join(this);
var TheText = document.getElementById("string");
TheText.innerText = "*".repeat(count);
}
</script>
</body>
</html>
Just use a regex:
w/ jQuery:
$('YOURELEMENT').html($('div').html().replace(/./g, '*'));
without:
var text = document.getElementById('YOURELEMENT').innerText;
document.getElementById('string').innerHTML = text.replace(/./g, '*')
To toggle :
Html input
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input id="password" type="password" />
The javascript
function toggleType(){
var inputEl = document.getElementById('password');
if(inputEl.type != "text"){
inputEl.type = "text";
}else{
inputEl.type = "password";
}
}
Working example: http://jsfiddle.net/3MRAX/1/
Sorry about this, OP, but I tried :( This is as far as I got.
Javascript
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
var hashes = s.hashCode;
lblValue.innerHTML = "The SHA256 hash is: " + hashes;
var text = document.getElementById("string");
text.innerHTML = "Original text: " + s;
}
function toggleType() {
var obj = document.getElementById('edValue');
if (obj.type == 'password') {
obj.type = 'text';
} else if(obj.type == 'text'){
obj.type = 'password';
}
}
HTML
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input
size="80"
type="text"
rows="7"
id="edValue"
type="text"
onkeyup="edValueKeyPress();">
<p id="string">Original text: </p>
<p id="lblValue">The SHA256 hash is: </p>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources