I have been spending a lot of time researching how to change a button href dynamically in my website using JS. I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.
I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.
One of the simplest solutions that should work was found here:
How to make option selection change button link?
I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed. I added window.onload() to prevent the JS from running before elements were loaded.
I am trying to do something similar with the following HTML & JS code:
HTML Code:
<input type="hidden" id="input-book-type" value="GlassCrystal">
<br><br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br><br>
<input id="input-project-title" value="Optional Project Title">
<br><br>
<a class="button" id="design-button" href="http://">Design Now</a>
JS Code:
window.onload = function() {
document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");
this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};
}
JS Fiddle:
https://jsfiddle.net/w65c9x2d/
I think your code to change the href is correct. However, the onload function is not immediately invoked for the code to work.
window.onload = function(e) {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var pagenum = document.getElementById("select-page-num");
var projtitle = document.getElementById("input-project-title");
document.getElementById("design-button").onclick = function() {
this.href = "http://design.framesmile.com/?sessionid=guest&ref=" + booktype.value + pagesize.value + "*projectName=" + projtitle.value + " / ";
console.log(this.href);
};
}();// invoke the function
<input type="hidden" id="input-book-type" type="" value="GlassCrystal">
<br>
<br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br>
<br>
<select id="select-page-num">
<option value="20">20</option>
<option value="22">22</option>
</select>
<br>
<br>
<input id="input-project-title" type="" value="Optional Project Title">
<br>
<br>
<a class="button" id="design-button" href="http://test/">Design Now</a>
Here is example code:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php";
return false;
};
</script>
I took this from here
Change your button to this:
<button class="button" id="design-button" onclick="redirect()">Design Now</button>
Now instead of using a link, simply do a function that will take the inputs and change the window.location.href (or whatever method you prefer) to change the page.
redirect(obj) {
window.location.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/"
}
Obviously change it to your liking :)
I recommend using jQuery.
$("#submit").on('click', function(event) {
event.preventDefault();
data = $("#link").val();
$("#frame").attr({
src: "http://"+data});
});
When the submit button is clicked, it changed the iframe url which changed the content of the iframe automatically.
I don't really understand what you are trying to ask, but try to modfiy the code above :)
Related
I have created a list with 6 options and users can only select one. I want that whenever a user selects an option from the list after they submit the form it directs them to a specific page depending on which selection.
Eg. I have 3 options
Facebook
Youtube
Twitter
If the user selects option 1 after submission it will direct them to the Facebook page, if they select option 2 it will direct them to a youtube page .. etc
This is quite simple. You just have to get the value from the selector & use JS to open that link. Check my solution for reference -
solution on JS Fiddle
function myFunction() {
let link =
document.getElementById("social").value
let fb = "https://facebook.com"
let tw = "https://twitter.com"
if(link == 'fb') {
window.open(fb);
} else if (link == 'tw') {
window.open(tw);
}
}
<select id="social">
<option value="fb">Facebook</option>
<option value="tw">Twitter</option>
</select>
<button onclick="myFunction()">
go to site
</button>
This somehow doesn't work here, working on JS Fiddle
<body>
<form>
<select name="" id="target">
<option value="facebook">Facebook</option>
<option value="youtube">Youtube</option>
<option value="twitter">Twitter</option>
</select>
<button type="button" id="sub_button">submit</button>
</form>
<script>
const data = {
facebook: 'https://facebook.com',
youtube: 'https://youtube.com',
twitter: 'https://twitter.com',
}
document.querySelector('#sub_button').onclick = function() {
let target = document.querySelector('#target').value;
window.location.href = data[target];
}
</script>
</body>
I have the following mock snippet:
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();
}
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>
<div style="float:left; margin-left:120px; margin-right: 40px; margin-top:70px;">
<br><br>
<input type="submit" value="Go to"><br><br>
<input type="reset" value="Reset Selection">
</div>
When I run this code what happens is that the href opens the correct url in a new tab, while the submit button opens the page I am currrently on in a new tab. I am not sure what I am doing wrong. Doesn't the document.formName.onsubmit suppose to make the submit button work the same as the href?
I tried to setup a fiddle with your code, and it worked well enough. But while doing it, I realized I had to move a piece of code around to avoid a small problem, so I'm going to guess that you are having the same situation.
My guess is that you have all your JavaScript code before the HTML. When this part
document.formName.onsubmit = function(){
this.action = generateLink();
}
is executed, the form does not exist yet, and the onsubmit can't be set (you should see an error about it in your console, too). When you click on your submit button later, the form has no action defined, and just goes to the same page (its default behaviour). Here's a fiddle having with this problem.
The simplest fix is moving the onsubmit assignment after the form. Here's the same fiddle, with the relevant code moved, that actually does what you expect.
You want to set an action="" on the
<form>
tag. When the form is submitted, it will submit to the page defined in action="". If not defined, it will submit back to the same page by default.
First time poster, long time forager. I have a system I am developing, cleaning up the process I would like to use pikaday.js to help users select the date insted of typing it in by hand.
The process:
From a dropdown (HTML) element, call to handleSelection(choice). handleSelection then looks at the option selected and either creates an input or a second select element with options. For two of the options I would like to create an input and add an onclick to kick pikadate...All I am getting is a input field with no call to the function on click, I can type in the date in the correct format and get a result so the post portion is working.
See code as follows:
JavaScript protion:
<script src='moment.js></script> <----used for date format only
<script src='pikaday.js></script>
<script>
function handleSelection(choice)
{
if(choice=='ordnum' || choice=='po' || choice=='serial' || choice=='asset') <----Works as intended
{
var a=document.getElementById('input');
var input=document.createElement('input');
input.type='text';
input.name='value';
a.appendChild(input);
}
if(choice=='varified')<----Works as intended
{
var a=document.getElementById('valid');
var valid=document.createElement('select');
valid.name='value';
valid.innerHTML="<option value='y'>Validated</option><option value='n'>Not Validated</option>";
a.appendChild(valid);
}
if(choice=='loc')<----Works as intended
{
var a=document.getElementById('valid');
var valid=document.createElement('select');
valid.name='value';
valid.innerHTML="<option value='loc0'>loc0</option><option value='loc1'>loc1</option><option value='loc2'>loc2</options><option value='loc3'>loc3</option><option value='loc4'>loc4</option><option value=';loc5'>loc5</option>";
a.appendChild(valid);
}
if(choice=='drcv' || choice=='disrv') <---Isn't working as intended!
{
var a=document.getElementById('input');
var input=document.createElement('input');
input.type='text';
input.name='value';
input.id='pkr';
input.onclick='getDate()'; <----Tried with quotes and with out, will not call out to getDate()
a.appendChild(input);
}
}
<script>
function getDate()
{
var picker = new Pikaday({field:docuemnt.getElementById('pkr'),format:'YYYYMMDD'});
</script>
}
}
</script>
HTML portion:
<body>
<form class='container' name='report' action='somepage' method='post'>
<select id='select' onChange='handleSelection(value)' name='opt'>
<option value="ordnum">Order Number</option>
<option value="po">Po Number</option>
<option value="drecv">Date Received</option>
<option value="disrv">Date In Service</option>
<option value='serial'>Serial Number</option>
<option value='asset'>Asset Tag</option>
<option value='loc'>Location</option>
<option value='varified'>Verified</option>
<option value='*' selected>All Systems</option>
</select>
<input type="submit" name="submit" value="Fetch..">
</p>
<p id='input'>
</p>
<p id='valid'>
</p>
</form>
</body>
</div>
</html>
Replace
input.onclick='getDate()';
with
input.addEventListener('click', getDate, false);
you could also use input.onclick = getDate;, but addEventListener is the preferred way of adding event listeners.
And make sure the getDate function is in scope, that means that it's either inside the same script tag as the event listener, or a script tag above the one containing the event listener.
Hoisting doesn't help across script tags.
So playing around a bit, seems style was the issue. I had a div style set in my original CSS and it seems that the div in the pikaday.css was going off of that position causing the stretched effect. I adjusted the percentage of the div in pickaday.css to 55% and now have the full effect that was wanted.
Main goal: I would like to create a dynamic form-building tool that allows the user to select certain options that, when chosen, enable subsequent inputs to occur.
An example of what I am describing:
Text Entry: Put in a Chapter Name.
Choose to add question
Choose Question type (mult. choice, check box, etc.)
Type in question.
Choose to add new question. If so, repeat ques. steps.
Choose to add new Chapter. If so, repeat add ques. options.
Submit whole content from above, and export (with the ultimate goal of being parsed/prepared into format for use, as per these guidelines (but that's for much later).
Example of what I have done so far: JS Fiddle
Note: Example is incomplete. Stopped because I realize I am building a mess and assume there is an easier/better way to do this.
Thanks in advance for any assistance that can be offered - I hope I was clear!
Kuan
Caveat: I am relatively new to programming/etc. That said, I feel I have searched quite a bit and there appears to be not much in regards to this specifically (the difficulty being primarily the nested nature of the questions, within the chapters).
JS Fiddle code:
<title>Dynamically build FT survey</title>
<script language="javascript">
function addChap(name) {
var element = document.createElement("li");
element.innerHTML = name;
var foo = document.getElementById("currentChapList");
//Append the element in page (in span).
foo.appendChild(element);
// Update drop down select lists
updateSelect();
}
function delChap() {
var foo = document.getElementById("currentChapList");
var allChildNodes = foo.childNodes;
var lastElem = allChildNodes.length - 1;
foo.removeChild(allChildNodes[lastElem]);
// Update drop down select lists
updateSelect();
}
function updateSelect() {
// First delete everything in the Chapter selection list
var currentChaps = document.getElementById("chapOptions");
var newFoo = document.getElementById("currentChapList");
for (i = 0; i < currentChaps.children.length; i++) {
currentChaps.remove(currentChaps.children[i]);
}
// Then re-add the remaining components from Chapter list
for (i = 0; i < newFoo.children.length; i++) {
nfCont = newFoo.children[i].innerHTML;
nfElem = document.createElement("option");
nfElem.innerHTML = nfCont;
currentChaps.appendChild(nfElem);
}
}
function addAns() {
//Create an input type dynamically.
var element = document.createElement("input");
var foo = document.getElementById("lastAns");
foo.appendChild(element);
}
function addQues() {
var allQues = document.getElementById("questionSubSect");
var newQues = document.createElement("div");
newQues.innerHTML = allQues.innerHTML;
//Append the element in page (in span).
allQues.appendChild(newQues);
}
</script>
</head>
<body>
<b>Current Chapter Index</b>
<br>
<ol id="currentChapList">
</ol>
<input type="text" style="width:400px" value="Enter Chapter Name" id="newChapName"/><br>
<input type="button" value="Add Chapter" onclick="addChap(newChapName.value)"/>
<input type="button" value="Delete Last Chapter" onclick="delChap()"/>
<br>
<br>
<b>Dynamically add element in form.</b>
<br>
Select the element and hit Add to add it in form.
<br>
<br>
<b>Chapter Builder</b>
<br>
<form>
Chapter Select:
<select id="chapOptions"></select>
<br>
<div id="questionSubSect">
<br>
Question ID:
<input type="text" style="width:400px" value="Enter Question"/>
<br>
Question:
<input type="text" style="width:400px" value="Enter Question"/>
<br>
Question Type:
<select name="element">
<option value="text">Checkbox</option>
<option value="text">Multiple Choice</option>
<option value="text">Open Text</option>
<option value="number">Open Number</option>
<option value="text">Ordered List</option>
<option value="image">Picture</option>
<option value="text">True or False</option>
</select>
<br>
Other open answer option:
<select name="element">
<option value="text">False</option>
<option value="text">True</option>
</select>
<br>
<br>
<span id="lastAns"></span>
<br>
<input type="button" value="Add Answer Option" onclick="addAns()"/>
<br>
<br>
</div>
<span id="lastQues"></span>
<input type="button" value="Add New Question" onclick="addQues()"/>
</form>
</body>
I have done some investigation about dynamic form. Here are some excellent open-source solutions. They usually do it in this way:
describe form structure as JSON in the backend.
then use one of the following libraries to render JSON to form in the frontend.
jsonform/jsonform
React JSONSchema Form (React) (demo)
I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" onsubmit="return myFunction();">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit">
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as <script type="text/javascript" src="script.js" />:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = document.getElementById('w1').innerHTML + "<h2> HEADING </h2>";
}
return false;
};
When I fill out the form and hit submit, the javascript correctly executes the function and adds "HEADING." However, when I press submit again, it adds "HEADING" a second time under the first instance of it.
How do I make it so that the page "refreshes" each time submit is pressed?
Thanks!
You can Use
window.location.reload();
In your Submit event code..
use jQuery, bind('submit', function(e){ e.preventDefault; ....; })
$('#date_form').submit(function(e){
e.preventDefault();
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false;
});
Found another way around the issue. I added the statement:
document.getElementById('week').innerHTML = "";
at the beginning of each call of the function. That way, every time the user clicks submit, the div is emptied out before it is repopulated.