Removing part of a form input's value with jQuery/JavaScript - javascript

I have a hidden input on my page like so:
<input type="hidden" name="required" value="name,town,tel,email">
As people fill in it's associated form, certain other fields become required (i.e. State becomes required when choosing "USA" from a Country dropdown).
I have two functions, one named addToRequiredFields() and one named removeFromRequiredFields() which fire as USA is selected/de-selected, however the removal one doesn't seem to be working, and I can't figure out why.
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
required += ',' + string;
$('input[name=required]').val(required);
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
required.replace(',' + string, '');
$('input[name=required]').val(required);
}
The function is called at .on('change') of the Select dropdown.

Though Its not a proper way to validate controls based on input value , I made a script for you .
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray.push(string)
$('input[name=required]').val(fieldsArray.join());
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray = fieldsArray.filter(function(item) {
return item !== string
})
$('input[name=required]').val(fieldsArray.join());
}
console.log($('input[name=required]').val())
addToRequiredFields("age")
console.log($('input[name=required]').val())
removeFromRequiredFields("name")
console.log($('input[name=required]').val())
removeFromRequiredFields("tel")
console.log($('input[name=required]').val())
addToRequiredFields("name")
console.log($('input[name=required]').val())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="hidden" name="required" value="name,town,tel,email">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>

Use the below login inside yourremove function.removeFromRequiredFields
//var requiredArr = $('input[name=required]').attr('value');
var requiredArr = "name,town,tel,email".split(',');
var rmvIndex = requiredArr.indexOf("tel")//"tel" is your string to be removed
var newArr = requiredArr.splice(rmvIndex, 1);
$('input').attr('value', newArr.join(','))// set value attribute after removing that string

Related

JS - I can get the value of input but not compare it

I'm learning JS and I'm trying to create a web game with javascript. The goal is simple: a flag is displayed at random, and the player must guess the name of the country associated with the flag.
The flag is randomly selected and displayed correctly, but I have a problem with the user interaction. I'd like to display "bad answer" in a <p> and if it's correct, display "good answer" (in a <p>), regenerate a flag and start again, indefinitely. The problem is that I can get the user's answer but i can't compare it to real answer and then display true or false.
I would like to know if someone could explain to me what is wrong and correct me please. Here is my code :
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function getVal() {
const inputValue = document.querySelector('input').value;
console.log(inputValue);
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data => data.json())
.then(data => {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
});
if (inputValue != data[randomInt].name.toLowerCase()) {
document.getElementsByClassName('result').class.add("result-false");
document.getElementsByClassName('result').innerHTML = 'Mauvaise Réponse';
} else if (inputValue == data[randomInt].name.toLowerCase()) {
document.getElementsByClassName('result').class.add("result-true");
document.getElementsByClassName('result').innerHTML = 'Bonne Réponse';
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess The Flag - </title>
<link rel="stylesheet" href="style.css">
<!-- <script type="text/js" src="app.js"></script> -->
</head>
<body>
<h1>GuessTheFlag</h1>
<div class="flagCanva">
<img id="flag" src="https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/images/KH.svg" alt="">
</div>
<input type="text" name="flagName">
<button type="submit" onclick="getVal()">Je valide</button>
<p class="result"></p><br>
<button onclick="getData()">Next</button>
</body>
</html>
The reason is because the scope of inputValue is inside the function getVal only.
So in function getData it doesn't know inputValue.
The scope is the perimeter where the variable is known, it could be globally, local to a function, or at other level. It depends where and how you declare the variable.
It's an important thing to understand in most of the computer langage.
Here's a refactored working version with some comments to help clear things out:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia"; // <= We need a global variable so that it can be set and accessed inside getVal() and getData()
function getVal() {
const inputValue = document.querySelector('input').value;
//>> Move the flag vs input comparison inside the input event handler:
if ( inputValue.toLowerCase() !== flag.toLowerCase()) { // <= Lowercasing both input and flag name to avoid case sensitive comparison failures
// Use `classList` instead of `class` to have access to the add() method
// Use `querySelector` to pick a single element instead of getElementsByClassName which returns a list of elements:
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
// No need for an else if here:
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
}
}
// TIP: Ideally the next function should be split into 2 functions:
// 1) fetchData(), runs once to grab the JSON
// 2) getRandomFlag(), runs on 'Next' click to get a random flag
// without re-fetching the JSON.
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data=>data.json())
.then(data=> {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name; // <= Set the value for the newly fetched flag name
});
}
Working demo:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia"; // <= We need a global variable so that it can be set and accessed inside getVal() and getData()
function getVal() {
const inputValue = document.querySelector('input').value;
//>> Move the flag vs input comparison inside the input event handler:
if(inputValue.toLowerCase() != flag.toLowerCase()) {
// Use `classList` instead of `class` to have access to the add() method
// Use `querySelector` to pick a single element instead of getElementsByClassName which returns a list of elements:
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
}
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data=>data.json())
.then(data=> {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess The Flag - </title>
<link rel="stylesheet" href="style.css">
<!-- <script type="text/js" src="app.js"></script> -->
</head>
<body>
<h1>GuessTheFlag</h1>
<div class="flagCanva">
<img width="100" id="flag" src="https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/images/KH.svg" alt="">
</div>
<input type="text" name="flagName">
<button type="submit" onclick="getVal()">Je valide</button>
<p class="result"></p><br>
<button onclick="getData()">Next</button>
</body>
</html>
There's a lot of refactoring that we can do (e.g. caching the selected elements, cache the json response to avoid re-fetching the data, removing global variables, etc.) to improve the code, but this is just a good start for a functional code.

Javascript to populate a form field with data extracted from URL Parameters

I am trying to use javascript to extract data from the URL parameter 'utm_source' and add it to a field on a form so that it is stored in my contact database for tracking purposes.
I had previously accomplished this on another site, but when trying to reuse the code it is not working for me.
The page is here (with the included URL parameter to be extracted):
https://members.travisraab.com/country-guitar-clinic-optin-1-1?utm_source=youtube&utm_medium=description
The desired result if for the 'traffic_source' field on my form to be populated with the value from the 'utm_source' URL parameter, in this case 'youtube'.
Here is the code I am using:
<script type="text/javascript">
function addSource() {
var fieldToChange = document.getElementsByName("form_submission[custom_4]");
var source = trafficSource();
fieldToChange.value = source;
}
var trafficSource = function() {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == "utm_source"){
return pair[1];
} else if (pair[0] == "gclid") {
return 'google';
}
}
return 'unknown';
}
document.onload = addSource();
</script>
fieldToChange is a NodeList so if you want to change the value property you need to specify the index number
So this should fix your code
fieldToChange[0].value = source;
You can take all the query params using new URLSearchParams(window.location.search) and get the particular query param using searchParams.get('utm_source') and then, store the value of utm_source in form field using document.getElementById("utmsource").value = param;.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="utmsource" />
<script>
let searchParams = new URLSearchParams(window.location.search)
let param = searchParams.get('utm_source')
document.getElementById("utmsource").value = param;
</script>
</body>
</html>

Selecting multiple arrays through a random generator

I'm creating multiple random generators. Once the first random generator selects a particular name the second will overide the first random generator and display the second random gernerators selection.
Here is what I have so far:
<!doctype html>
<html>
<head>
<script>
function postmessage() {
var firstnames = ["John", "Jacob", ];
var firstname = firstnames[Math.floor(Math.random() * firstnames.length)];
function pickAnother(John) {
if (John != firstnames) {
run(sndnames);
}
}
pickAnother (firstnames);
var sndnames = ["Eric", "Conroy", ];
var sndname = sndnames[Math.floor(Math.random() * sndnames.length)];
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<input type="button" value="Get Recruit" onclick="postmessage();" />
<div id="recruit"></div>
</body>
</html>
I managed to get an alart message from another code, but I would like to display the sndnames like the firstnames.

dropdown menu in javascript with adding new elements

I am new in javascript and in this moment I am trying to use "Basic DOM and JS". I am doing a dropdown menu, what gets his elements from an array. There is an input field, where you can add new items into the array.I also made a button to push and save the item into array and make the dropdown automatically with DOM.
My problem if you push the button, it makes always a new dropdown menu. Otherwise the array works good, but I need just one dropdown menu with the items of array. I think this problem comes out at listing with ul li too. Here is my whole code and thanks for helping
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
var menu = document.createElement("select");
document.body.appendChild(menu);
for(var i = 0; i<select.length; i++){
var option = document.createElement("option");
var text = document.createTextNode(select[i]);
option.appendChild(text);
menu.appendChild(option);
}
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
You are creating the select tag every time array() is invoked. So create select tag once and rest of the time create option tag when array() is invoked. Here is your solution.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
var selectIsCreated = false;
var menu;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
if(!selectIsCreated){
menu = document.createElement("select");
document.body.appendChild(menu);
selectIsCreated = true;
}
var option = document.createElement("option");
var text = document.createTextNode(select[select.length-1]);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
So Suman already answered your question, but in terms of simplifying the code or the approach, I think you could take a different approach by removing the use of the "select" array entirely. The array isn't necessary to add in the value to the select list, as you can get everything you need from the input element, so you just need to work on adding the option to the actual select DOM element.
Here is the desired functionality re-factored a bit with this in mind.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
function createSelect() {
select = document.createElement('select');
select.id = 'select';
document.body.appendChild(select);
return document.getElementById('select');
}
function addOption(){
var input = document.getElementById("input");
var value = input.value;
// This will attempt to grab the 'select' element, but if it finds
// that it doesn't exist (i.e. getElementById returns a "falsy" value)
// then it will return the value of the createSelect function.
// This could also be done with more explicit "if" statements
var menu = document.getElementById('select') || createSelect();
// The same effect could be achieved by running this code:
/*
var menu = document.getElementById('select');
// If the select element hasn't been created/added to the page yet,
// then the above call to getElementById will return a "falsy" value,
// i.e. a value that isn't a strict boolean type but JS will treat it
// as "false".
if (!menu) {
menu = createSelect();
}
*/
var option = document.createElement("option");
var text = document.createTextNode(value);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<!--
I've renamed the array() function since we don't even
have an array anymore
-->
<input onclick="addOption()" type="button" value="Add">
</body>
</html>
You can see this in action on this jsFiddle

Getting value of textarea returns undefined

I have an html form and a js script that gets the value of a textarea. However, when I'm getting the value of the textarea with javascript it return "undefined".
I have the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery/jquery-1.9.1.min.js"></script>
<script src="contentForm.js"></script>
</head>
<body>
<form method="post" >
<textarea name ="editor" id="editBox" rows="5" cols="2">type</textarea>
<p><input type="submit" id="submit" value="Submit"></p>
</form>
</body>
</html>
JS
function add() {
$("#submit").click(function() {
document.write("hello motto");
var message = "start js";
console.log(message);
var contents = $("#editBox");
var a = contents.val();
if(a === undefined) {
console.log("contents undefined");
}
console.log(contents);
var item = {"id":"12", "content": contents};
var obj = JSON.stringify(item);
var obj2 = JSON.parse(obj);
console.log("you have arrived");
document.write(obj2.id);
});
}
$(document).ready(function () {
add();
});
I tried the following to get the value of the textarea:
var content = $("#editBox").val();
and
var contents = $("textarea#editBox").val();
The val of the textarea is always undefined, with each of the methods I tried.
Is there another method for retrieving the value of a textarea?
Running document.write on a closed document will open a new document and destroy the DOM of the existing one.
This destroys the textarea, so when you try to retrieve it to get the value, it does not exist.
Remove the line document.write("hello motto");.
Use DOM manipulation to edit the existing document, instead of writing a new one.

Categories

Resources