I want to display a picture after an option in my dropdown menu is selected. The picture will depend on the value the user selected. I tried to do this (bear in mind that I haven't even learned JavaScript yet, I just know 2 or 3 basic functions thanks to Google):
showpic.js
document.getElementById('item').onchange = function(){
document.getElementById('ipic').style.display = "block";
document.getElementById('ipic').innerHTML = "<img src='http://example.com/pics/" + this.value + "'.png";
};
items.php without the PHP code for your convenience
<div id='ia'>
<form action='add_items.php' method='post'>
Username: <input name='username' type='username'> <br />
Password: <input name='password' type='password'> <br />
Item: <select name='item' id='item'>
<option value='100'>Example</option>
<option value='200'>Example 2</option>
</select>
<script src='sort.js'></script> <br/> <!-- Sorts Items in Alphabetical Order -->
<div id='ipic'></div>
<script src='showpic.js'></script>
<input name='add' type='submit' value='Add Item'>
</form>
</div>
But that didn't work. I heard it was something to do with "XMLHTTPREQUEST" & AJAX. Can anyone help me? I don't know JavaScript.
I'm not sure what you think you need AJAX for, but your script almost works!
"<img src='http://example.com/pics/" + this.value + "'.png";
This part is broken, because you start an <img element but you never close it (/>).
Change it to this:
document.getElementById('ipic').innerHTML = "<img src='http://example.com/pics/" + this.value + "'.png' />";
Now it will try to load a picture named [value].png in that div
Related
I'm trying to put together a little script to save some typing for some stuff we type repetitively at my office. Basically the idea is that you select a couple options and then the page displays a paragraph inserting some of the selected custom text at various places.
Anyways, this is what I have, and it isn't working. I've tried putting some console.logs in the JavaScript, and they aren't doing anything. Why?
<!DOCTYPE html>
<html>
<head>
<script>
function write() {
var name1 = document.getElementById("firstname");
var name = name1.options[name1.selectedIndex].text;
var gender1 = document.getElementById("gender");
var gender = gender1.options[gender1.selectedIndex].text;
var authentication1 = document.getElementById("authentication");
var name = authentication1.options[authentication1.selectedIndex].text;
var answer = name + gender + authentication; // There will be some other text added in here eventually
document.getElementById("text").innerHTML += answer;
}
</script>
</head>
<body>
<form>
<input type="text" name="firstname" placeholder="Name"><br /><br />
<select name="gender">
<option value="his">His</option>
<option value="her">Her</option>
</select><br /><br />
<select name="authentication">
<option value="questions">security questions</option>
<option value="firstyear">first year attended</option>
<option value="birthday">birthday and mailing address</option>
</select><br /><br />
<input type="submit" value="Submit" onClick="write(); return false;">
</form>
<h2 id="text"></h2>
</body>
</html>
write is a method of document. It will never work, it will just paint a blank page
function writeThis() {
var name = document.forms[0].firstname.value;
var gender = document.forms[0].gender.options[document.forms[0].gender.selectedIndex].text;
var authentication = document.forms[0].authentication.options[document.forms[0].authentication.selectedIndex].text;
document.getElementById("text").innerHTML += (name + " " + gender + " " + authentication);
}
I renamed your function as writeThis() so make sure in your html :
<input type="submit" value="Submit" onClick="writeThis();return false">
Also, the new function show you how to get the values. Review it that way you learn how to do it. Finally, it's a better practice if you close always your html tags <input /> not <input>.
And the fiddle: http://jsfiddle.net/xr7vqsfm/4/
All right. So I'm coding after A LOOONG TIME, and I just went on to codecademy to get a bit refreshed with javascript. So I learnt something I didn't know before : OOP.
Help. I tried something. Will include the JSfiddle. But I don't know why, it doesn't work.
Nevermind my Idiocy, I will complete the code as soon as I know what the problem in the prev code was. I have alot to do in that. I also want to learn PHP to make a kind of phone directory!
I have also NOT included the CSS, but that hardly matters.
What the code should do, is that everytime a user fills up the form and clicks submit, it should append the values in a '#results' div. Not doing anything. Help?
Also, nevermind the two password fields. I will write the code for validating the form once I am clear with this problem.
THANK YOU IN ADVANCE.
JSFIDDLE : http://jsfiddle.net/Ns66V/1/
HTML -- >
<html>
<head>
<link rel="stylesheet" href='style.css'>
<script type="type/javascript" src='jquery.js'></script>
<script type="type/javascript" src='js.js'></script>
<title>Form JS</title>
</head>
<body>
<div class='container'>
<h1>Create an ID! It's absolutely <strong>FREE!</strong></H1>
<div id='form'><form action='get'>
<input name='fname' type='text' placeholder='First Name'><br>
<input name='lname' type='text' placeholder='Last Name'><br>
<input name='email' type='email' placeholder='Email Address'><br>
<input name='passw' type='password' placeholder='Password'>
<input name='Again' id='last' type='password' placeholder='Again!'><br>
<select name='gender'>
<option value='male'>Male</option>
<option value='female'>Female</option>
<option value='other'>Other</option>
</select>
<div id='submit'><strong>SUBMIT IT!</strong></div>
</form>
</div>
<div class='results'>
<div class='vals' id='intro'>
<div class='srn item'>#</div>
<div class='bigitem item'>FULL NAME</div>
<div class='bigitem item'>EMAIL ADDRESS</div>
<div class='gender item'>Gender</div>
</div>
<div class='vals'>
<div class='srn item'>#</div>
<div class='bigitem item'>FULL NAME</div>
<div class='bigitem item'>EMAIL ADDRESS</div>
<div class='gender item'>Gender</div>
</div>
</div>
</div>
</body>
</html>
JS (JQuery) -->
$(document).ready(function(){
function Person(fname,lname,email,passw,gend){
this.fname = fname;
this.lname = lname;
this.email = email;
this.passw = passw;
this.gend = gend;
};
var numPeople = 0; //Setting the number of people var.
$('#submit').click(function(){
var fname = $('input[name=fname]').val(), //SETS VALUES OF ALL THE INPUTS
lname = $('input[name=lname]').val(), //SETS VALUES OF ALL THE INPUTS
email = $('input[name=email]').val(), //SETS VALUES OF ALL THE INPUTS
passw = $('input[name=passw]').val(), //SETS VALUES OF ALL THE INPUTS
gend = $('select[name=gender]').val(); //SETS VALUES OF ALL THE INPUTS
var People = new Array(); //Definin
numPeople++;
People[numPeople] = new Person(fname,lname,email,passw,gend);
$('.results').append(People[numPeople].fname + People[numPeople].lname + People[numPeople].email + People[numPeople].passw + People[numPeople].gend);
}); //#SUBMIT.CLICK() END
});
OOP isn't entirely needed in this case. The problems is that you need to use #results, and you need to close your button along with other tags.
HTML
<button id='submit' type='button'><strong>SUBMIT IT!</strong></button>
JS
$('#results').append(...);
Here is a Fiddle example, added a <br /> at the end.
Also get and post are for a forms method attribute. action is where the form sends the data. So you probably want:
<form method="get"></form>
Check http://jsfiddle.net/Ns66V/4/
The button tag was not closed and the content was appended to the button and
$('#submit').click(function()
should be replaced with
$('#submit').on('click', function()
Now seems to work.
Of course you should improve how you append the content though - use html tags to separate each information.
I'm creating a quiz website for a class, and I am having trouble formatting the page where the user creates questions. I would like to have additional information pertaining a specific question type pop up when the user clicks a radio button. I would then like to have even more additional information pop up if the user clicks a button created in the initial additional information.
So it'd start off looking like this
then it'd look like this
then once the user clicked the Add Option button a few times, it'd look like this
To achieve this I am trying to use jquery to add the new content. However, I can't seem to get that content to display. Here's the current code
In jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="QuestionsCreate.js"></script>
<meta charset="UTF-8">
<title>Quiz Creation</title>
</head>
<body>
<h1>Create Your Quiz</h1>
<form action="QuestionsCreateServlet" method="post">
<h2>Question Type</h2>
<input type="radio" name="type" class="type" id="multipleChoice"
value="multipleChoice" />
<label for="multipleChoice">Multiple Choice</label><br/>
<input type="radio" name="type" class="type" id="fillBlank"
value="fillBlank" />
<label for="fillBlank">Fill-in-the-Blank</label><br/>
<input type="radio" name="type" class="type" id="pictureResponse"
value="pictureResponse" />
<label for="pictureRsponse">Picture Response</label><br/>
<input type="radio" name="type" class="type" id="textResponse"
value="textResponse" />
<label for="textResponse">Text Response</label><hr/>
<div class="jspf"></div>
<input type="submit" name="button" id="button" value="Finish" />
</form>
</body>
</html>
In javascript
$(document).ready(function() {
$(".type").click(function(){
$(".jspf").html("<jsp:include page='WEB-INF/" +
$(".type").attr("value") + ".jspf' />");
$("#button").attr("value", "Add");
});
var nOptions = 1;
$("#add-option").click(function(){
++nOptions;
$(".options").append("<input type='checkbox' name='option" +
nOptions + "' value='" + nOptions + "' /> " +
"<input name='name" + nOptions + "' /><br />");
});
var nBlanks = 1;
$("#add-answer").click(function() {
++nBlanks;
$(".fill-blank-answer").append("<input name='answer" + nBlanks +
"' /><br/>");
});
});
Sample jspf
<h3>Question</h3>
<input name="prompt" />
<h3>Options</h3>
Check the options that denote the correct answer<br/>
<div class="options">
<input type='checkbox' name='option1' value='1' />
<input name='name1' /><br />
</div>
<input type="button" value="Add Option" id="add-option" /><hr/>
I've also tried to move the jspf code into the javascript, but that didn't work either.
Is there a way I can add content dynamically to my webpage based off of dynamically added content? Thanks in advanced!
The issue you're having is you're trying to inject server-side JSP tags into a client's browser. Take this line for example:
$(".jspf").html("<jsp:include page='WEB-INF/" +
$(".type").attr("value") + ".jspf' />");
Once that line of javascript has executed, the CLIENT's brower now has the markup:
<div class="jspf"><jsp:include page="wEB-INF/pictureResponse.jspf" /></div>
Broswers don't know what to do with <jsp:include> tags, so they just silently ignore them.
What you need to do is map the jspf you're trying to include to a url and use something like:
$(".jspf").load("/fragments/pictureResponse.jspf");
$.load sends an AJAX request to from the client browser back to the server, retrieves a bit of HTML from the server, then inserts that in to the elements that match the CSS selector ".jspf".
You also have an issue with your initial click handler.
$(".type").attr("value")
$.attr always returns the attribute value of the first matched element, so no matter what the user clicked, that line is going to evaluate to "multipleChoice". What you probably want to do is:
$(this).attr("value")
In the context of a click handler, "this" is going to refer to what the user just clicked.
UPDATE
Here's how I would add the "add option" click handler once the secondary content has been loaded:
$('jspf').load('/fragments/pictureResponse.jspf', function() {
$('#add-option').click(function() {
nOptions++;
$('.options').append('<input type="checkbox" name="option' + nOptions +
'" value="' + nOptions + '" /> <input name="name' + nOptions + '" /><br />");
});
});
$.get("${ctx}/store/terminalApply/applyTemplate?terminalType=${terminalType}&index="+num, function(data){
$("#contentDiv").append(data);
});
data was a page content
I have the following javascript code:
game.bind('gameover', function(seconds) {
setTimeout(function() {
var rank = game.getRank(seconds);
scorecard.find('.time').text(seconds + ' sec');
scorecard.find('.rank').text(rank[0]);
scorecard.find('.byline').text(rank[1]);
...more code
In the following div this data is displayed (so the js script is working):
<div class="inner">
<h3>Nice job! Your time:</h3>
<h1 class="wobble time"><!-- 15 seconds --></h1>
<h2 class="rank"><!-- Friendly Mallard --></h2>
<h3 class="byline"><!-- (That's pretty good) --></h3>
</div>
Now I want to put the results also in a form so I can post it to the a database (mysql). So I've added a form and put it in the same div:
<form id="form" action="updatescore.php" method="post">
<input type="text" id="time" name="time" value="" />
<input type="text" id="rank" name="rank" value="" />
<input type="text" id="byline" name="byline" value="" />
</form>
Now in the JS I've copied the lines (e.g. scorecard.find('.time').text(seconds + ' sec');) and changed it to look for the id, so . becomes # and passed it in the js like:
scorecard.find('.time').text(seconds + ' sec');
scorecard.find('#time').text(seconds + ' sec');
etc
So this should work I think, but the form inputs stay empty. What am I doing wrong?
Kind regards,
Maurice
If you are just looking to move js variables into your database via updatescore.php you don't need to use a form at all! You can do it with AJAX.
var scoreData = {
time : time,
rank : rank[0],
byline : rank[1]
};
$.post('updatescore.php', scoreData); //done!
Use val() instead of text() for setting the values
I'm working on a tagging system and I want users to be able to add and remove tags on the page. for each one thats added I am displaying a small div with the tag and an x to remove the tag. I have the adding functionality working, but I'm not sure how to go about making it so I can remove them. I also have a hidden input which should hold all the values so that when the information is submitted I can use it.
Heres my attempt that doesn't work:
function tagsremove(tag) {
$('#hiddentags').val().replace('/'+tag+'\,\s/', '');
$("#tagdiv-"+tag.replace(" ","_")).fadeOut('normal', function(){
$(this).remove();
});
}
$(document).ready(function(){
$('#tagbutton').click(function(){
var tags = $('#tagsbox').val().split(", ");
for (var i in tags) {
$('#hiddentags').val($('#hiddentags').val() + tags[i] +", ");
$('#curtags').append("<div class='tag'>" + tags[i] + " <a href='#' id='#tagdiv-"+tags[i].replace(" ", "_")+"' onclick='tagsremove(\""+tags[i]+"\");' >x</a></div>");
}
$('#tagsbox').val('');
});
});
heres the html to go with it:
<div class='statbox'>
<form method='post' action='post.php' id='writeform'>
<p class='subtitle'>Title</p>
<input type='text' name='title' id='titlebox' /><br />
<p class='subtitle'>Body</p>
<textarea id='postbox' name='body' rows='10'></textarea><br />
<p class='subtitle'>Tags</p>
<input type='text' id='tagsbox' /><input type='button' id='tagbutton' value='Add' />
<p class='subsubtitle'>Seperate by commas (eg. "programming, work, job")</p>
<div class='subsubtitle' id='curtags'>Current Tags:</div>
<input type='hidden' value='' name='tags' id='hiddentags' />
</form>
</div>
Make each of your tag divs have a relevant ID. For, say, the "play pen balls" tag, your ID could be "tagdiv-play_pen_balls". Now you can just do
function removeTag(tag) {
$("#tagdiv-"+tag.replace(" ","_")).remove();
}
to remove the visible div.
(I'm not sure if that's what you were asking for, though...)
Instead of using .val('') you should be using .html('');
http://docs.jquery.com/Manipulation