Accessing action and value attributes using JS - javascript

let dealer={
name : document.getElementById('dealer-name'),
submit : document.getElementById('dealer-save'),
};
let dnames=['str', 'name'];
dealer.name.addEventListener('keyup', check);
function check(){
for (let i=0; i<dnames.length; i++){
if (dnames[i] === dealer.name.value) {
console.log('same');
dealer.submit.value = "Update";
} else {
dealer.submit.value = "Save";
}
};
}
<!DOCTYPE>
<html>
<body>
<form action="/php/newdealer.php" id="addDealer">
<input required type="text" id="dealer-name">
<input type="submit" value="Save" id="dealer-save">
</form>
</body>
</html>
Summary of the Code:
In the webpage a simple form is shown consisting an input field and submit button. Each time a character is inputted in the input field check() function is executed.
If the value in input field matches with any of the element in dnames[] array Then value of submit button is expected to be 'update' and the string 'same' is logged into console, else if the value in input field doesn't matches with any of the element in dnames[] array Then value of submit button is expected to be 'save'
Problem:
When i type in "str" in the input field 'same' is logged into the console as expected but the value of the submit button doesn't changes to 'update'. Why dealer.submit.value="Update" failed to work?

The problem is that your loop keeps running after it encounters the right answer.
str is the first element in the array, so it updates the button value to "Update"
the loop goes to the next value in the array, name
It's not the same as the input value, so it updates the button value back to 'Save'
It all runs almost immediately, so it looks like it's not uploading.
You can solve this adding a break or return after assigning "Update" to the button, like this:
let dealer={
name : document.getElementById('dealer-name'),
submit : document.getElementById('dealer-save'),
};
let dnames=['str', 'name'];
dealer.name.addEventListener('keyup', check);
function check(){
for (let i=0; i<dnames.length; i++){
if (dnames[i] === dealer.name.value) {
console.log('same');
dealer.submit.value = "Update";
break; // add this to your code
} else {
dealer.submit.value = "Save";
}
};
}

Related

Not working, Javascript validating text input before button click

The code is suppose to validate an input and then execute a function when a button is clicked, but it is not working and the console does not suggest why. The only difference is that when you take away toString() on input it says it is not a function.
This is my first big project at university and not really sure which part is wrong?
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
const trimmed = input.toString().trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}
Function to be executed
function addRow() {
something...
}
validating if this function is true then execute this function.
function validate(){
if(check()){
addRow();
}
}
document.getElementById('input').addEventListener('input', check);
document.getElementById('btn').addEventListener('click', validate);
Html
<input type="text" id="input" class="input" autofocus autocomplete="off" placeholder="Add items in your list..">
<button id='btn' class="add">+</button>
Although the input variable is not declared in your code, I assume that it is supposed to represent the <input type="text"> element.
With the validation step you should validate the value of the input, not the input itself.
But your logic is still missing something. The else statement will never be reached. If the value is empty then the state will be set to '' and the function is stopped. If there is a value, and it has been trimmed, then you're always left with a string with a value in it and there for your value is truthy. So the else would not make without an if statement which would allow the value to be false when the validation is incorrect.
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
// Trim the value.
const trimmed = value.trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}

Confirm deletion alert code not quite right

I'm creating a simple todo app in JS and i've added an alert box to confirm deletion when usr clicks the delete button. If user clicks 'OK' it deletes fine, and if clicked 'Cancel' it won't delete but it creates another empty
li tag under it.
Something is not quite right with my deleteItem function but I can't figure out what, tried adding an else statement same thing happens. Any help with an explanation will be greatly appreciate (I'm a noob in JS as you can tell). Thanks!
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>
What you need to change is: make the buttons of the list items of type button. They default value of type for a button is submit, which will submit the whole form, which will trigger your issue.
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)" type="button">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>
You forgot to close the form tag after the button, as a result your ourForm listener gets called even for confirmation box.
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
</form>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>

Add search field result to an empty array

Every time a user types something into a search field, I want it to be added to an empty array I've created. For some reason, my current code only adds an empty string to the array but not the string itself:
Javascript
var myArray=[];
var submit = document.getElementById("submit");
var result = document.getElementById("result").value;
submit.addEventListener("click", function() {
myArray.push(result);
})
HTML
<input id="result" type="text"><button id="submit">Submit</button>

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

Could someone please explain a piece of Javascript code?

I am doing a project in school, and as part of that I had to include radio buttons in my html form. Below is the Javascript code which some parts I don't quite understand. The code works fine. Could someone plz give me an explanation of how the code works.
var check = false;
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
if (document.ExamEntry.Level[i].checked)
{
var radiovalue = document.ExamEntry.Level[i].value;
check =true;
var usermessage=confirm("You have chosen: ".concat(radiovalue));
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
<!--I understand the code below, its just some parts of the above code.
if (check ==false)
{
msg+="ERROR:You must select an entry level \n";
document.getElementById ('Levelcell'). style.color = "red";
result = false;
}
I added comments to help explain this:
var check = false;
// set a variable 'i' from 0 up to the ExamEntry level length (so for each radio)
// if there are 10 items, this code will run 10 times, each time with 'i' a different value from 0 to 9
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
// is the radio button checked? If so, do the stuff inside. If not, skip this part
if (document.ExamEntry.Level[i].checked)
{
// set variable radiovalue to the value of the particular radio button
var radiovalue = document.ExamEntry.Level[i].value;
// set the check variable to true
check =true;
// ask the user to confirm the value and set usermessage based on confirmation
var usermessage=confirm("You have chosen: ".concat(radiovalue));
// if the user hits no on confirm, it will reset the radiomessage to blank and check to false
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
All form elements are bound to the global HTML document variable. So somewhere on the page there must be a form with the name of ExamEntry:
<form name='ExamEntry' id='ExamEntry` ...
The next part refers to an element in the form. Since they are expecting a radio button, Level must be an input of type radio:
<label name="Level" id="1" type="radio" ....
<label name="Level" id="2" type="radio" ....
The loop iterates through all radio buttons. If the the button is checked, it grabs the checked value, and shows that message. If it does not find a checked button, then it displays an error message.

Categories

Resources