I have the following mock form and I'd like the link to either disappear, or reset to the default selection.
HTML :
<form name="formName" target="_blank">
<div style="margin: 0 auto; width:600px;">
<div style="float:left;"><span>Pick AAA</span><br>
<select id="AAA" onchange="showLink()">
<option value="11">Eleven</option>
<option value="12">Twelve</option>
<option value="13">Thirteen</option>
<option value="14">Fourteen</option>
</select>
</div>
<div style="float:right;"><span>Pick BBB</span><br>
<select id="BBB" onchange="showLink()">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
</div>
<br><br>
<div style="float:left; margin-left:120px; margin-right: 40px; margin-top:70px;">
<input type="submit" value="Go to"><br><br>
<input type="reset" value="Reset Selection">
</div>
JS :
function generateLink()
{
var A = document.getElementById('AAA').value;
var B = document.getElementById('BBB').value;
if(B == "1" || B == "2")
link ='http://' + B + '.' + A + '.domain';
else if(B == "3" || B == "4")
link ='http://' + B + '.' + A + '.domain/link.jsp';
else
link ='/404.html';
return link;
}
function showLink()
{
var link = generateLink();
document.getElementById("link").href = link;
document.getElementById("link").innerHTML = link;
}
document.formName.onsubmit = function(){
this.action = generateLink();
}
What happens now is that when I hit Reset Selection, the select elements are being reset but the link itself doesn't disappear due to the onchange command. Does anyone know how I can reset the link as well?
Try:
document.formName.onreset = function(){
document.getElementById('link').innerHTML = ''
}
In General, Reset method restores a form element's default values. This method does the same thing as clicking the form's reset button.
Why Link is not reset to default?
Link is Anchor Tag which is not part of form Field. Form Reset Feature is to reset Form Fields not other elements like anchor, p, h1-h6.
Take a look at the working code.
function generateLink() {
var A = document.getElementById('AAA').value;
var B = document.getElementById('BBB').value;
if (B == "1" || B == "2")
link = 'http://' + B + '.' + A + '.domain';
else if (B == "3" || B == "4")
link = 'http://' + B + '.' + A + '.domain/link.jsp';
else
link = '/404.html';
return link;
}
function showLink() {
var link = generateLink();
document.getElementById("link").href = link;
document.getElementById("link").innerHTML = link;
}
document.formName.onsubmit = function() {
this.action = generateLink();
}
document.formName.onreset = function(){
document.getElementById('link').innerHTML = ''
}
<form name="formName" target="_blank">
<div style="margin: 0 auto; width:600px;">
<div style="float:left;"><span>Pick AAA</span><br>
<select id="AAA" onchange="showLink()">
<option value="11">Eleven</option>
<option value="12">Twelve</option>
<option value="13">Thirteen</option>
<option value="14">Fourteen</option>
</select>
</div>
<div style="float:right;"><span>Pick BBB</span><br>
<select id="BBB" onchange="showLink()">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
</div>
<br><br>
<div style="float:left; margin-left:120px; margin-right: 40px; margin-top:70px;">
<input type="submit" value="Go to"><br><br>
<input type="reset" value="Reset Selection">
</div>
</form>
Other Improvments, if your code is not test code.
Avoid Inline Styles and keep it as styles.
Use Form Field label.
Instead of span tags. Avoid <br> element and manage with CSS Styles.
Use addEventListener method.
You're creating the link programmatically , so you need to remove it programmatically, too:
document.formName.onreset = function(){
let linkEl = document.getElementById("link");
linkElement.href = '';
linkElement.innerHTML= '';
}
reset() method only resets the data. You need to hide the link yourself.
Related
i am trying to create simple Rock,paper, scissor game,
but i have some case, i want to have access on div which id is firstplayer, also this div has increment function, which increases value by 1... if in form field i choose 12, an when i press "firstplayer" and it value will increase to 12, i want to console.log("you win"), i tried a lot, but it's not works, what can i do, to solve this problem?
<!-----my html---->
<form action="#">
<label for="numbers">Game up to:</label>
<select id="form" >
<option value="7" >7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="submit" id="submit">
</form>
<div>
<h4 onclick="increment()">Firstplayer</h4>
<div id="firstplayer">
</div>
</div>
///my js
const firsPlayer = document.getElementById("firstplayer");
const Form = document.getElementById("submit");
form.addEventListener("input", function(event){
event.preventDefault();
if (event.target.value==="12"){
return playerwin()
}
})
var x=0;
function increment(){
return firsPlayer.innerHTML = ++x;
}
// i tried this but it's not working
function playerwin(){
if(firsPlayer.childNodes[0].nodeValue == 12){
console.log("you win")
}
}
my code here https://codepen.io/kafka2001/pen/LYpmexe
Not exactly sure what the final result should be but please check the code below that illustrates how it could basically work. Just adapt it to your needs to obtain the desired result.
const firsPlayer = document.getElementById("firstplayer");
const select = document.getElementById("select");
var x = 0;
function increment() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + 1;
}
function addSelected() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + Number(select.value);
}
function playerwin() {
if (firsPlayer.childNodes[0].nodeValue == 12) {
console.log("you win")
}
}
<select id="select">
<option value="7">7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="button" onClick="increment();" value="Increment">
<div>
<h4 onclick="addSelected()">Firstplayer</h4>
<div id="firstplayer"></div>
</div>
I am a beginner with Javascript.
I have written code for getting the values from selected option and it works fine.
My question is after selecting all the three options, if I click on "submit"
button it should go to the next page.
can someone please help on this?
Condition to be executed while redirecting to another page:
if(strUser == 'AAA') && (strUser1 == 'DDD') && (strUser1 == 'GGG'))
{
window.location.replace("sample4.html");
}
else if(strUser == 'BBB') && (strUser1 == 'EEE') && (strUser1 == 'HHH'))
{
window.location.replace("sample5.html");
}
else
{
alert("please select all the 3 options");
}
}
Code:
<body
style="background-image: url(./img/ford3.png); background-size: cover;">
<h3>welcome user!!</h3>
<button class="ssystem">System</button>
<button class="sub">Sub-System</button>
<button class="subsub">Sub-Sub-System</button>
<div class="box">
<select name="select1" id="sys" onchange="showData();">
<option value="1">AAA</option>
<option value="2">BBB</option>
<option value="3">CCC</option>
</select>
</div>
<div class="box1">
<select id="sub" onchange="showData();">
<option value="4">DDD</option>
<option value="5">EEE</option>
<option value="6">FFF</option>
</select>
</div>
<div class="box2">
<select id="sub1" onchange="showData();">
<option value="7">GGG</option>
<option value="8">HHH</option>
<option value="9">III</option>
</select>
</div>
<input type="submit" value="Submit" id="button">
<script>
function showData() {
var e = document.getElementById("sys");
var e1 = document.getElementById("sub");
var e2 = document.getElementById("sub1");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
//var value = e1.options[e1.selectedIndex].value; //for index
//alert(value);
var strUser1 = e1.options[e1.selectedIndex].text;
alert(strUser1);
var strUser2 = e2.options[e2.selectedIndex].text;
alert(strUser2);
</script>
</body>
Solution
There were a few things wrong with your code.
Firstly, you want to make your state variables (values that can change) of a higher scope so you can share them between your functions. These are the values of your <select> html elements.
Since all your default values are at index zero, we can just default to that selected index value upon initialisation of the page.
We can extract the <select> DOM element into a variable with document.getElementById() and then get the selected option value out of it like so:
var strUser = document.getElementById("sys").options[0].text;.
Another thing is that your IF statements were incorrectly written. I amended this for example here:
if (strUser == 'AAA' && strUser1 == 'DDD' && strUser2 == 'GGG')
I left the alerts in there so you can see the sequential flow of the code.
Additionally, I moved the Javascript to a separate file and imported it through the <script> tag. This is a nice separation of concerns.
A link to a JSFiddle is here for a more visual effect of how the code works.
I hope this helps.
HTML
<body
style="background-image: url(./img/ford3.png); background-size: cover;">
<h3>welcome user!!</h3>
<button class="ssystem">System</button>
<button class="sub">Sub-System</button>
<button class="subsub">Sub-Sub-System</button>
<div class="box">
<select name="select1" id="sys" onchange="showData();">
<option value="1">AAA</option>
<option value="2">BBB</option>
<option value="3">CCC</option>
</select>
</div>
<div class="box1">
<select id="sub" onchange="showData();">
<option value="4">DDD</option>
<option value="5">EEE</option>
<option value="6">FFF</option>
</select>
</div>
<div class="box2">
<select id="sub1" onchange="showData()">
<option value="7">GGG</option>
<option value="8">HHH</option>
<option value="9">III</option>
</select>
</div>
<input type="submit" value="Submit" id="button" onclick="goToNextPage()">
<script src="./script.js"></script>
</body>
Javascript
var strUser = document.getElementById("sys").options[0].text;
var strUser1 = document.getElementById("sub").options[0].text;
var strUser2 = document.getElementById("sub1").options[0].text;
function showData() {
var e = document.getElementById("sys");
var e1 = document.getElementById("sub");
var e2 = document.getElementById("sub1");
strUser = e.options[e.selectedIndex].text;
alert(strUser);
strUser1 = e1.options[e1.selectedIndex].text;
alert(strUser1);
strUser2 = e2.options[e2.selectedIndex].text;
alert(strUser2);
}
function goToNextPage() {
if (strUser == 'AAA' && strUser1 == 'DDD' && strUser2 == 'GGG') {
window.location.replace("sample4.html");
}
else if (strUser == 'BBB' && strUser1 == 'EEE' && strUser2 == 'HHH') {
window.location.replace("sample5.html");
}
else {
alert("please select all the 3 options");
}
}
Ok, I have the following HTML source:
<form method="post" action="/" id="search">
<input list="animals" name="animal">
<datalist id="animals">
<option label="Alaskan Malamute" data-id="d8c" value="Dog">
<option label="Siberian Husky" data-id="w30" value="Dog">
<option label="Aegean" data-id="rxx" value="Cat">
</datalist>
</form>
And the JS
function doKeyUp(e) {
if (e.preventDefault) e.preventDefault();
if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 ) {return;}
var input = document.getElementById("animal");
var search_after = input.value.trim();
var form = document.getElementsByTagName("form")[0];
var datalist = document.getElementsByTagName('datalist')[0];
if (search_after.length >= 2) {
if (e.keyCode == 13 && search_after.length >= 3) {
var id = "value of data-id";
// How to obtain and submit the `data-id` of the selected option.
document.getElementById("search").submit();
}
}
} // dokeyup
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("search").onsubmit = function (e) {
console.log("SUBMIT");
return false;
};
document.addEventListener( "keyup", doKeyUp, true);
});
When the user then selects an option, how do I get the data-id of the selected <option> - which is the actual data I want to submit and process on the server side.
This is a project where I'm trying to write everything by my self, no jQuery this time.
Know I can do console.log(datalist.options[1]);, but can not figure how I obtain the selected index.
Update March 4:
Must ask again, no one who has any tips for me ?
Still not figured this out, and have really run out of ideas...
The last I've tried stopped at, before the form submission:
for (var i=0; i<document.getElementById('animals').options.length; i++) {
if (document.getElementById('animals').options[i].value == document.getElementsByName("animal")[0].value) {
var id = document.getElementById('animals').options[i].getAttribute('data-id');
break;
}
}
Is it in any way possible to get the selected index of the chosen option - or am I still on the wrong path ?
This above stops at the first element, anyway.
Check this answer as jquery solution .. & sorry for late reply .
$(function(){
$('#p').click(function(){
console.log($("#animals option[value='" + $('#someid').val() + "']").attr('data-id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/" id="search">
<input list="animals" name="animal" id="someid">
<datalist id="animals">
<option label="Alaskan Malamute" data-id="d8c" value="Dog">
<option label="Siberian Husky" data-id="w30" value="Dog">
<option label="Aegean" data-id="rxx" value="Cat">
</datalist>
<span id="p">Click</span>
</form>
the value of the data-id attribute of the selected < option > in a datalist can be accessed from the DOM datalist object, like this
<input list="animals" id="input-animal" name="animal">
<datalist id="animals">
<option label="Alaskan Malamute" data-id="d8c" value="Dog">
<option label="Siberian Husky" data-id="w30" value="Dog">
<option label="Aegean" data-id="rxx" value="Cat">
</datalist>
animals.options.namedItem( input-animal.value ).getAttribute('data-id')
namedItem() is a method which returns the element from the collection with the specified id.
Russel Newton's solution using namedItem almost worked for me. Here is an adjusted solution that worked, using the name attribute on the option tags. (Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/namedItem)
var form = document.getElementById('dataForm');
form.addEventListener('submit', validateform);
function validateform() {
event.preventDefault();
var selectedOption = dataListId.options.namedItem(inputId.value);
if (selectedOption) {
var selectedId = selectedOption.getAttribute('data-id');
var result = "Country ID: " + selectedId;
console.log({selectedId});
} else {
var result = "No ID available for value: " + inputId.value;
}
document.getElementById('resultID').textContent = result;
// Can also use :
// inputElement = document.getElementById("inputId");
// listElement = document.getElementById("dataListId");
}
div.resultID {
color: #85144b;
font-weight: bold;
margin-top: 30px;
margin-left: 20px;
}
<form id="dataForm">
<input id="inputId" list="dataListId" value="" placeholder="Choose a country">
<datalist id="dataListId">
<option data-id="1" name="Country A">Country A</option>
<option data-id="36" name="Country B">Country B</option>
<option data-id="59" name="Country C">Country C</option>
</datalist>
<button id="submitButton" type="submit">Submit</button>
<div id="resultID" class="resultID"></div>
</form>
https://kodingkantor.blogspot.co.id/2018/03/get-data-id-in-datalist-option.html
console.log($("#locations option[value='" + $('#location1').val() + "']").attr('data-id'));
Without jQuery!
When input value has changed, data attributes of input field get merged:
document.querySelector('#animal').addEventListener('input', (e) => {
Object.assign(e.target.dataset, document.querySelector('#' + e.target.getAttribute('list') + ' option[value="' + e.target.value + '"]').dataset);
console.log('dataset of input changed: ', e.target.dataset)
});
<input list="animals" id="animal" data-id="xxx">
<datalist id="animals">
<option value="Alaskan Malamute" data-id="123" data-alpha="abc">
<option value="Siberian Husky" data-id="456" data-alpha="def">
<option value="Aegean" data-id="789" data-alpha="ghi">
</datalist>
Could someone help me with this little javascript. I want the rersult to show in NA only when option value 2 is selected. I want 11" to show will show. Need a simple script to output custom text based on value text. I do know i have value="2" listed twice. I cannot use the value field.
<select id="sizing-change" onchange="myFunction()">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>
<script>
function myFunction() {
if(document.getElementById("test").value == "11") {
document.getElementById("finalsize").innerHTML = "Size: 11";
}
}
</script>
You can check the text of the option like
function myFunction() {
var el = document.getElementById("sizing-change");
if (el.options[el.selectedIndex].text.trim() == '11"') {
document.getElementById("finalsize").innerHTML = "Size: 11";
} else {
document.getElementById("finalsize").innerHTML = "NA";
}
}
<select id="sizing-change" onchange="myFunction()">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>
If you can alter the value field of option to different values(which you should) then you can try this:
<select id="sizing-change" onchange="myFunction()">
<option value="12">12</option>
<option value="11" id="test">11</option>
</select>
<div class="sizefinal">Suggested Size: <span id="finalsize">NA</span>
</div>
<script>
function myFunction() {
if (document.getElementById("sizing-change").value == 11) {
document.getElementById("finalsize").innerHTML = "Size: 11";
}
}
</script>
Demo: http://jsfiddle.net/GCu2D/784/
var finalsize = document.querySelector('#finalsize');
var sizingChange = document.querySelector('#sizing-change')
var testOption = sizingChange.querySelector('#test');
myFunction(sizingChange);
function myFunction(element) {
var checked = element.querySelector(':checked');
if (checked == testOption) {
finalsize.innerHTML = "Size: " + element.querySelector(':checked').text;
} else {
finalsize.innerHTML = 'NA';
}
}
<select id="sizing-change" onchange="myFunction(this)">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>
I have a div inside my form which is filled with a field based on the value of the select box above it. This field always comes back as 'null' when submitted, I put a div around other parts of the form to test if it was in fact the div itself and each field with a div around it kept coming back as 'null'.
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
So the code above works fine its when i add a div inside i get 'null' like below;
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<div id='testdiv'>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
Whats my best way around this? and how would I go about doing it?
EDIT: The Div 'readnode' is called and placed inside the form when needed, replacing the div 'writenode' which is seen inside the form above. This div works perfectly fine. When i add another div (testdiv) inside the 'readnode' any fields placed inside the new div (testdiv) always come back as null when using $_get.
EDIT2:
Function that puts the readnode in place of the writenode,
<script type="text/javascript">
/* Set the counter that will increase every time
the user adds a new language*/
var counter = 0;
function addlanguage()
{
// Ask the user for input
var language = prompt("Language Name","");
if (language == "" || language == null)
{
alert("Please enter a language.");
}
else
{
counter++;
// Find the element to be copied
var newNode = document.getElementById('readnode').cloneNode(true);
newNode.id = '';
newNode.style.display = 'block';
var newField = newNode.childNodes;
// Give all fields a unique value
for (var i=0;i<newField.length;i++)
{
var theName = newField[i].name;
var theId = newField[i].id;
if (theName)
{
newField[i].name = theName + counter;
}
if (theId == "languagename")
{
// Change the field to the user input
newField[i].innerHTML = language;
}
if (theName == "lang")
{
// Replace the hidden field with the correct language
newField[i].value = language;
}
}
// Insert the elements
var insertHere = document.getElementById('writenode');
insertHere.parentNode.insertBefore(newNode,insertHere);
}
}
</script>
and this is the php;
<?php
if ($_GET["time1"] == null)
{ ?>
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<?php
}
else
{
$final = 0;
$i = 1;
while($final == 0)
{
$gettime = "time" . $i;
$getRank = "rank" . $i;
$time = $_GET[$gettime];
$rank = $_GET[$getRank];
if ($language == "")
{
$final = 1;
}
if ($final == 0)
{
// Show the user the input
echo("<p>Your <strong>$time</strong> is <strong>$rank</strong>.</p>");
}
$i++;
}
} ?>
When you put it inside a div, it's no longer part of newNode.childNodes, so you never get to set the name properly. You'll have to check childs of childs or use jQuery to simplify things.
for (var i=0;i<newField.length;i++)
{
var subField = newField.childNodes;
for (var i=0;i<subField.length;i++) {
var theName = subField[i].name;
var theId = subField[i].id;
// ...
}
}