Create a Name list with Input Field to add Names - javascript

I tried to create a Javascript List with an Input Field to add new Names. My Goal is it to have a name list where i can add new ones. I want also to not add a value if the input field is empty.
My current Problem is that if i add a new name and i press the button all the already created names are added once again.
I dont know why! I am fairly new to Javascript and Jquery.
var names = ['Peter', 'Thomas', 'Nick', 'James'];
var x = 1;
$(document).ready(function() {
function display_array() {
$.each(names, function(index, value) {
$('#names').append(value + '<br />');
});
}
display_array();
$('#insert').click(function() {
var name = document.getElementById('name');
if(name != ''){
name[x] = name;
display_array();
}
x = x + 1;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="name" type="text">
<input id="insert" type="button" value='Insert new Name'>
<div id="names"></div>

const names = ['Peter', 'Thomas', 'Nick', 'James'];
function display_array() {
$('#names').empty(); // Clear list before rendering
$.each(names, function(index, value) {
$('#names').append(value + '<br />');
});
}
$(document).ready(function() {
display_array();
$('#insert').click(function() {
const name = document.getElementById('name').value; // Get value of input field
if(name != ''){
names.push(name); // Push to names list
display_array(); // Re-render list
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="name" type="text">
<input id="insert" type="button" value='Insert new Name'>
<div id="names"></div>

it is because you always append values
you should stick either to javascript or jquery. your code is a mixture between the two and this might puzzle you.
var names = ['Peter', 'Thomas', 'Nick', 'James'];
var x = 1;
$(document).ready(function() {
function display_array() {
$('#names').html(names.join('<br/>'));
}
display_array();
$('#insert').click(function() {
var name = $('#name');
if(name !== ''){
names.push(name.val());
display_array();
}
});
});

Your code does not work for three reasons:
You have to clear the shown namelist on display_array() using $('#names').empty();, otherwise you will add the whole list again and again
With var name = document.getElementById('name') you're setting a DOM-element to name. But you need the value of it. For this you can use document.getElementById('name').value; or with jQuerys $('#name').val();
They way you want to push the new name into the array will not work. Use names.push(name) instead
I think codecademy could be interesting for you, to get in touch with the JavaScript basics. Its really cool and for free. :)
var names = ['Peter', 'Thomas', 'Nick', 'James'];
$(document).ready(function() {
function display_array() {
$('#names').empty();
$.each(names, function(index, value) {
$('#names').append(value + '<br />');
});
}
display_array();
$('#insert').click(function() {
var name = $('#name').val();
if(name != ''){
names.push(name);
display_array();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="name" type="text">
<input id="insert" type="button" value='Insert new Name'>
<div id="names"></div>

Related

prevent users from entering duplicate entries in text inputs in javascript

I have a DOM in which I want to prevent users from entering duplicate entries in html text input.
The above DOM is not in user's control. It is coming through php.
At this moment, I am focussing only on name="code[]".
This is what I have tried:
$(function(){
$('input[name^="code"]').change(function() {
var $current = $(this);
$('input[name^="code"]').each(function() {
if ($(this).val() == $current.val())
{
alert('Duplicate code Found!');
}
});
});
});
Problem Statement:
I am wondering what changes I should make in javascript code above so that when a duplicate code is entered, alert message "Duplicate code Found" should come up.
you need to add an eventlistener to each item, not an eventlistener for all. Then count inputs with same value, if there's more than 1, it's a duplicate.
Also ignore not-filled inputs.
Check following snippet:
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
$('#createInput').on('click', function(){
let newInput = document.createElement("input");
newInput.name = 'code[]';
newInput.type = 'text';
newInput.className = 'whatever';
$('#inputGroup').append(newInput);
// repeat the eventlistener again:
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputGroup">
<input name="code-1" type="text" class="whatever">
<input name="code-2" type="text" class="whatever2">
<input name="code-3" type="text" class="whatever3">
</div>
<input type="button" id="createInput" value="Add input">
Edit:
now works with dynamically created elements. The class 'e' works as flag to not insert 2 event listeners to the same node element, otherwise they will run in cascade, provoking unwanted behaviour.
You can use something like this, that converts the jQuery object to an Array to map the values and find duplicates. I added an option to add a style to the duplicated inputs, so the user knows which ones are duplicated.
function checkDuplicates(){
var codes = $('input[name^="code"]').toArray().map(function(element){
return element.value;
})
var duplicates = codes.some(function(element, index, self){
return element && codes.indexOf(element) !== index;
});
return duplicates;
}
function flagDuplicates(){
var inputs = $('input[name^="code"]').toArray();
var codes = inputs.map(function(element){
return element.value;
});
var duplicates = 0;
codes.forEach(function(element, index){
var duplicate = element && codes.indexOf(element) !== index;
if(duplicate){
inputs[index].style.backgroundColor = "red";
inputs[codes.indexOf(element)].style.backgroundColor = "red";
duplicates++
}
});
return duplicates;
}
$('input[name^="code"]').on("change", function(){
//var duplicates = checkDuplicates(); // use this if you only need to show if there are duplicates, but not highlight which ones
var duplicates = flagDuplicates(); // use this to flag duplicates
if(duplicates){
alert(duplicates+" duplicate code(s)");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="code-1" type="text">
<input name="code-2" type="text">
<input name="code-3" type="text">

How do you save multiple key value pairs to one cookie with JavaScript/jQuery?

I have a form with multiple checkboxes in it and when I click them, I want to add/remove the key-value pairs (name of the input + true/false) in one single cookie.
When I click on the checkboxes only the first pair gets shown in console.log.
This is what I ended up with so far:
HTML:
<form class="form">
<input class="input" name="expert_id_1" type="checkbox" />
<input class="input" name="expert_id_2" type="checkbox" />
<input class="input" name="expert_id_3" type="checkbox" />
<input class="input" name="expert_id_4" type="checkbox" />
</form>
JS:
function setCookie() {
var customObject = {};
var inputName = $('.input').attr('name');
customObject[inputName] = $('.input').prop('checked');
var jsonString = JSON.stringify(customObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function getCookie() {
var nameValueArray = document.cookie.split('=');
var customObject = JSON.parse(nameValueArray[1]);
$('.input').prop('checked') = customObject[inputName];
}
$('.input').each(function() {
$(this).on('click', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
setCookie();
});
});
Your cookie is being overrided and it might only store the first checkbox info. Also to set the prop value, you have to pass it as a second parameter.
This should update the cookie when clicked and also be able to set the values from the cookie.
function updateCookie($input) {
var cookieObject = getCookieObject();
var inputName = $input.attr('name');
cookieObject[inputName] = $input.attr('value');
var jsonString = JSON.stringify(cookieObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function setFromCookie(){
var cookieObject = getCookieObject();
for(var inputName in cookieObject)
if(cookieObject.hasOwnProperty(inputName))
$(`.input[name="${inputName}"]`).prop('checked', cookieObject[inputName]);
}
function getCookieObject() {
var nameValueArray = document.cookie.split('=');
var cookieObject = {};
if(nameValueArray.length >= 2)
cookieObject = JSON.parse(nameValueArray[1]);
return cookieObject;
}
$('.input').each(function() {
var $this = $(this);
$this.on('click', function() {
$this.attr('value', String($this.is(':checked')))
updateCookie($this);
});
});
Although I would recomend you to use a URLSearchParams object to encode and decode the parameters, since you are relying on the fact that "=" is not inside the JSON string.

getElementByID.readOnly in array

Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?
script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function(){
var index, len;
$.get('/SomeList.txt', function(data){
var SomeList = data.split('\n');
for (index = 0, len = SomeList.length; index < len; index++) {
document.getElementById(SomeList[index]).readOnly = true;
}
});
});
});
</script>
and txt file contains name of input ID:
TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
Assuming you have some elements with the given IDs you must check if the element exists first before doing
document.getElementById(SomeList[index]).readOnly = true;
so replace that line with
var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
return;
}
myElement.readOnly = true;
That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.
var dataArray = [
'TextFieldName',
'TextFieldEmailxxxxx',
'TextFieldDepartment',
'TextFieldOffice'
];
dataArray.forEach(function(id){
var myElement = document.getElementById(id);
if(myElement == null) {
return;
}
myElement.readOnly = true;
});
<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
document.getElementById(id_array[i]).readOnly = true;
}
Email: <input type="text" id="email" value="test#mail.com"><br>
Country: <input type="text" id="country" value="Norway" >
it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

How to map an object to form fields?

I have an object like this:
var settings = {
Name: "Fairy Tail",
Feature:
{
Translate: true,
Share: true
}
}
And a form
<form>
<input type="text" name="Name" />
<input type="checkbox" name="Feature.Translate" />
<input type="checkbox" name="Feature.Share" />
</form>
How can I make the object fill the form "automatically" (without setting the value of each field by hand)?
You can do it this way (jsfiddle for a more sophisticated example), assuming you have settings variable set first:
var assignValue = function(n, v){
var field = jQuery('form input[name="'+n+'"]');
if (field.attr('type')=='text'){
field.val(v);
} else if (field.attr('type')=='checkbox') {
field.prop('checked',v);
}
}
var assignSettings = function(list, prefix){
if (typeof prefix != 'undefined'){
prefix += '.';
}else{
prefix = '';
}
for (item in list){
if ((typeof list[item]=='string')||(typeof list[item]=='boolean')){
assignValue(prefix+item,list[item]);
}else if(typeof list[item]=='object'){
var n1 = item;
assignSettings(list[n1],prefix+n1);
}
}
}
assignSettings(settings);
And this solution is not as limited as other solutions in the versions I have seen so far - it supports the case you have given and can be easily expanded to support different types of fields and more levels.
var inputs = $('form input[type="checkbox"]');
$.each(settings.Feature, function(key, val) {
inputs.filter('[name="Feature.' + key + '"]')[0].checked = val;
});
Example: http://jsfiddle.net/9z928/
If you also wanted the text field filled in:
var inputs = $('form input');
inputs.first().val( settings.Name );
$.each(settings.Feature, function(key, val) {
inputs.filter('[name="Feature.' + key + '"]')[0].checked = val;
});
Example: http://jsfiddle.net/9z928/1/
Might be worth giving this a try: http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html
You can use this JavaScript library for mapping Obeject to form fields name and vice versa.
Object-Form-Mapping

Categories

Resources