Displaying different Images with multiple buttons in Javascript - javascript

I'm a newbie to Javascript and I'm trying to put together a program that displays one image at a time, and when a different button is pressed a new image is shown to replace the old one. I'm hoping that you all could help me out with this one!
Here's what I have so far:
<html>
<body>
<p>My favorite Beers!</p>
<style type="text/css">
.show{display:block;}
.hide{display:none;}
</style>
<script type="text/javascript">
function showImg() {
var obj = document.getElementById('picture1','picture2','picture3','picture4','picture5','picture6','picture7','picture8','picture9','picture10');
obj.className = 'show';
}
</script>
<body>
<img id="picture1" src="lost abbey.png"class="show">
<input type="button" onclick = "showImg()" value= "Lost And Found">
<img id="picture2" src="stone-gtipa-bottle.jpg" class="hide">
<input type="button" onclick = "showImg('stone-gtipa-bottle.jpg')" value= "Green Tea IPA">
<img id="picture3" src="belching beaver.jpg" class="hide">
<input type="button" onclick = "showImg()" value= "Belching Beaver">
<img id="picture4" src="boardwalk_insta.jpg" class="hide">
<input type="button" onclick = "showImg()" value= "Karl Strauss">
<img id="picture5" src="el conquistador epa.jpg" class="hide">
<input type="button" onclick = "showImg()" value= "Mission Brewery">
<img id="Picture6" src="fallbrook.png" class="hide">
<input type="button" onclick = "showImg()" value= "Fallbrook Brewery">
<img id="Picture7" src='gordon biersch golden ale.jpg' class="hide">
<input type="button" onclick = "showImg()" value= "Gordon Biersch">
<img id="Picture8" src="grumpy bear.jpg" class="hide">
<input type="button" onclick = "showImg()" value= "Grizzly Paw">
<img id="Picture10" src="Moderntimes.jpg" class="hide">
<input type="button" onclick = "showImg()" value= "Modern Times">
<img id="Picture9" src="lost-abbey-agave-maria1.png" class="hide">
<input type="button" onclick = "showImg()" value= "Agave Maria">
</body>
</html>

You can do this in a better way (don't predefine all the images and don't set them all to hide, but whatever, the following script and HTML will do more or less what you want.
<script>
function showImg( id ) {
// hide previously shown image
for ( i = 1; i < 10; i++) {
var obj = document.getElementById( "picture" + i );
if (obj != null)
obj.className = 'hide';
}
var obj = document.getElementById( "picture" + id );
if (obj != null)
obj.className = 'show';
}
</script>
<style type="text/css">
.show{display:block;}
.hide{display:none;}
</style>
<p>My favorite Beers!</p>
<img id="picture1" src="lost abbey.png" title="1" class="show">
<input type="button" onclick="showImg(1);" value="Lost And Found">
<img id="picture2" src="stone-gtipa-bottle.jpg" title="2" class="hide">
<input type="button" onclick="showImg(2);" value="Green Tea IPA">
<img id="picture3" src="belching beaver.jpg" title="3" class="hide">
<input type="button" onclick="showImg(3);" value= "Belching Beaver">
<img id="picture4" src="boardwalk_insta.jpg" title="4" class="hide">
<input type="button" onclick = "showImg(4)" value= "Karl Strauss">
<img id="picture5" src="el conquistador epa.jpg" title="5" class="hide">
<input type="button" onclick = "showImg(5)" value= "Mission Brewery">
<img id="picture6" src="fallbrook.png" class="hide">
<input type="button" onclick = "showImg(6)" value= "Fallbrook Brewery">
<img id="picture7" src='gordon biersch golden ale.jpg' class="hide">
<input type="button" onclick = "showImg(7)" value= "Gordon Biersch">
<img id="picture8" src="grumpy bear.jpg" class="hide">
<input type="button" onclick = "showImg(8)" value= "Grizzly Paw">
<img id="picture10" src="Moderntimes.jpg" class="hide">
<input type="button" onclick = "showImg(10)" value= "Modern Times">
<img id="picture9" src="lost-abbey-agave-maria1.png" class="hide">
<input type="button" onclick = "showImg(9)" value= "Agave Maria">
An alternative, would be to have a single <img> anchor, and then the buttons would change the src of the <img> based on what the <input type="button" onclick="showImg();>" sends in as src rather than a number.
My goal has been to make a solution which is closely based on what you already have.

Related

How to show a list of random image via click event?

I have coded a basic php web page where I want random images from my images folder to be displayed once a button has been clicked.
However no images are being displayed and I cannot find the issue with my code.
var myImg = ["fruit1.jpg", "fruit2.jpg", "fruit3.jpg", "fruit4.jpg", "fruit5.jpg", "fruit6.jpg"];
function displayImage() {
var num = Math.floor(Math.random() * 6);
document.picture.src = myImg[num];
}
<div class="wrapper">
<div class="boxa">A1
<input onclick="displayImage();" type=button value="Display Random Image">
<img src="" name="picture" />
</div>
<div class="boxb">B
<input onclick="displayImage();" type=button value="Display Random Image">
<img src="" name="picture" />
</div>
<div class="boxc">C
<input onclick="displayImage();" type=button value="Display Random Image">
<img src="" name="picture" />
</div>
</div>
document.picture.src doesn't exist.
When you click on the <input>, you want to access the <img ...> and that's the nextElementSibling. Therefore, you need an argument in the function, too.
Example
var myImg = ["fruit1.jpg", "fruit2.jpg", "fruit3.jpg", "fruit4.jpg", "fruit5.jpg", "fruit6.jpg"];
function displayImage(el) {
var num = Math.floor(Math.random() * 6);
el.nextElementSibling.src = myImg[num];
}
<div class="wrapper">
<div class="boxa">A1
<input onclick="displayImage(this);" type=button value="Display Random Image">
<img src="" name="picture" />
</div>
<div class="boxb">B
<input onclick="displayImage(this);" type=button value="Display Random Image">
<img src="" name="picture" />
</div>
<div class="boxc">C
<input onclick="displayImage(this);" type=button value="Display Random Image">
<img src="" name="picture" />
</div>
</div>
A better generic solution would be
var myImg = ["fruit1.jpg", "fruit2.jpg", "fruit3.jpg", "fruit4.jpg", "fruit5.jpg", "fruit6.jpg"];
var selector = "div[class^=box] input";
function El(selector) {
return document.querySelectorAll(selector);
}
function setRandImg(img, images) {
var rand = Math.floor(Math.random() * images.length);
img.src = images[rand];
}
function addEventListeners(els, type, fn) {
for (var i = 0; i < els.length; i += 1) {
var el = els[i];
el.addEventListener(type, fn);
}
}
function displayImg() {
setRandImg(this.nextElementSibling, myImg);
}
addEventListeners(El(selector), "click", displayImg);
<div class="wrapper">
<div class="boxa">A1
<input type=button value="Display Random Image">
<img src="" name="picture" />
</div>
<div class="boxb">B
<input type=button value="Display Random Image">
<img src="" name="picture" />
</div>
<div class="boxc">C
<input type=button value="Display Random Image">
<img src="" name="picture" />
</div>
</div>

JavaScript how to send different entities but keeping the same id?

Suppose I have 2 areas separated by div containers, I need to send the Id values from the different areas, locally when the function is called in that container.
extract:
<script>
document.getElementById('compare_name").innerHTML = "Changed";
</script>
<div class = "details>
<span id="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
<div class = "details">
<span id="compare_name">no2</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
You cannot use same ID for more than one element. you can use name instead like below:
<script>
var x = document.getElementsByName("compare_name");
for(var i = 0; i < x.length ; i++){
x[i].innerHTML = "Changed";
}
</script>
<div class = "details>
<span id="compare_name" name="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
<div class = "details">
<span id="compare_name" name="compare_name">no2</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
As others indicates that, to follow the rule, the ID attribute should not be duplicated, but it doesn't matter if you don't rely on it.
I guess the asker might only need to change one text inside the div which is clicked, not all the spans, so just a little change.
<html>
<head>
<title>Test</title>
<script>
function add_compare(el) {
var divChildEles = el.parentNode.parentNode.childNodes;
for (var i=0; i<divChildEles.length; i++) {
if (divChildEles[i].nodeType==1 && divChildEles[i].nodeName=="SPAN") {
//console.log(divChildEles[i].innerText);
divChildEles[i].innerText='changed';
}
}
}
</script>
</head>
<body>
<div class = "details">
<span id="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare(this)">
</form>
</div>
<div class = "details">
<span id="compare_name">no2</span>
<form id="view-details1">
<input type="button" value="Add to Compare" onclick="add_compare(this)">
</form>
</div>
</body>
</html>
id in JavaScript must be unique. instead, you can give them a class with the same name
<script>
var x=document.getElementByClassName('compare_name");
for(var i=0;i<x.lengh;i++)
x[i].innerHTML = "Changed"
</script>
<div class = "details>
<span class="compare_name">no1</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>
<div class = "details">
<span class="compare_name">no2</span>
<form id="view-details0">
<input type="button" value="Add to Compare" onclick="add_compare()">
</form>
</div>

Javascript MVC for a simple app does not work

Reffering to my previous question (about simple pocket calculator), I try to rewrite it using MVC pattermn. I understand the basics of MVC but to implement it is pretty difficult for a beginner. so my html code is :
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/SimpleCalculator.css">
<script type="text/javascript" src = "js/SC_Controller.js"></script>
<script type="text/javascript" src = "js/SC_Model.js"></script>
<script type="text/javascript">
new SC_Controller().init();
</script>
</head>
<body>
<h2>Simple Calculator</h2>
<div class="box">
<div class="display"><input type="text" readonly size="18" id="displayId"></div>
<div class="keys">
<p><input type="button" class="button black" value="7">
<input type="button" class="button black" value="8">
<input type="button" class="button black" value="9">
<input type="button" class="button orange" value="/">
</p>
<p><input type="button" class="button black" value="4">
<input type="button" class="button black" value="5">
<input type="button" class="button black" value="6">
<input type="button" class="button orange" value="*">
</p>
<p><input type="button" class="button black" value="1">
<input type="button" class="button black" value="2">
<input type="button" class="button black" value="3">
<input type="button" class="button orange" value="-">
</p>
<p><input type="button" class="button black0" value="0">
<input type="button" class="button black" value=".">
<input type="button" class="button orange" value="+"></p>
<p><input type="button" class="button greenc" value="C">
<input type="button" class="button yelloweq" value="="></p>
</div>
</div>
</body>
and my two JS filController.js are :
SC_Controller.js
var SC_Controller = function(scModel){
var model = scModel || new SC_Model();
var s = "";
function clicked(){
s += model.getValue();
alert(s);
model.setValue(s);
}
function init(){
document.getElementsByClassName("button").onclick = clicked;
}
return {
init : init;
model : model
};
};
and
SC_Model.js
var SC_Model = function(){
function getValue(){
return(document.getElementsByClassName('button').value);
}
function setValue(val){
document.getElementById('displayId').value = val;
}
return{
getValue : getValue,
setvalue : setValue
};
};
To implement a MVC pattern, I googled and found an example. I tried to adapt it to my calculator code, but launching the HTML, when I click a key the alert box in SC_Controller.js does not pop up. I can not understand why. Could you help me ?
The document.getElementsByClassName("button") returns a collection of nodes
(see https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName).
You need to iterate over them when applying the click handler as well as when requestion their .value.
For instance, the
document.getElementsByClassName("button").onclick = clicked;
should be
var buttons = document.getElementsByClassName("button");
for(var i=0;i<buttons.length;i++)
buttons[i].onclick = clicked;

re-adding HTML into a DIV using JavaScript/JQuery

Hi All I have the following Div as seen below:
<div id = '1'>
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
when the user clicks on the button, I want to add the following Divs again:
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
Is this possible to achieve with JavaScript or the jQuery onclick function?
You can use clone method with insertAfter:
HTML:
<div id='1'>
<div class="template"> <!-- mark a clone target -->
...
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
Demo: http://jsfiddle.net/VcBrz/
Try this:
<script>
$(document).ready(function(){
var divID='abc';
var $mainDiv=$('#'+divID);
$mainDiv.find('input[name="addNewRow"]').eq(0).click(function(){
var $this=$(this);
var $div=$(this).parents('div').eq(0).prev('div').clone();
$this.parents('div').eq(0).prev('div').after($div);
});
});
</script>
Demo: http://jsfiddle.net/xT62m/
The best way is to clone that div which you want to add to div#1.
For easier manipulation, please add classes to div with button and to each div which represents row.
HTML:
<div id = 'id1'>
<div class='row'>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div class='buttonHolder'>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
Javascript (with jQuery):
$(document).ready(function(){
$('.buttonHolder input[type=button]').on('click', function(){
//Clone existing row to template.
var row = $('#id1 .row').first().clone();
//Clear template
$('input', row).val('');
$(row).insertBefore('.buttonHolder input[type=button]');
});
});
jsFiddle example: http://jsfiddle.net/9Z2RT/1/
make html like this:
<div id="container">
<div class= 'template'>
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
</div>
</div>
<div>
<input type="button" name="addNewRow" id="btnAddRow" value="Add Row" />
</div>
Click Function:
$('#btnAddRow').click(function(){
var row = $('.template').first().clone();
$('#container').append(row);
});
Here is Fiddle DEMO
The simpliest way will be:
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<script>
var m_TextToAdd = '<div> ';
m_TextToAdd += '<div> ';
m_TextToAdd += ' <label class="right inline">Response:</label>';
m_TextToAdd += '</div>';
m_TextToAdd += '<div>';
m_TextToAdd += ' <input type="text" name="responseText[]" value="" maxlength="400" /> ';
m_TextToAdd += '</div>';
m_TextToAdd += ' <div>';
m_TextToAdd += ' <input type="radio" name="responseRadio[]" value="" />';
m_TextToAdd += ' </div>';
m_TextToAdd += '</div>';
function AddContent() {
document.getElementById('div1').innerHTML += m_TextToAdd;
}
</script>
</head>
<body>
<div id = 'div1'>
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" onclick='AddContent();'/>
</div>
</div>
</body>
</html>
Anyhow, it heart my eyes to see it :-)
I think the next code is more readable:
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<script type='text/javascript'>
function AddContent() {
var dest = document.getElementById('div1');
//add label
var lbl = document.createElement('label');
lbl.innerHTML = 'Response:';
lbl.className = 'right inline';
dest.appendChild(lbl);
//add line break
dest.appendChild(document.createElement('br'));
//add text input
var input = document.createElement('input');
input.type = 'text';
input.name = 'responseText[]';
input.maxlength="400";
dest.appendChild(input);
//add line break
dest.appendChild(document.createElement('br'));
//add radio button
input = document.createElement('input');
input.type="radio";
input.name="responseRadio[]";
dest.appendChild(input);
//add line break
dest.appendChild(document.createElement('br'));
}
</script>
</head>
<body>
<div id = 'div1'>
<label class="right inline">Response:</label>
<br>
<input class='nextLine' type="text" name="responseText[]" value="" maxlength="400" />
<br>
<input class='nextLine' type="radio" name="responseRadio[]" value="" />
<br>
<input class='nextLine' type="button" name="addNewRow" value="Add Row" onclick='AddContent();'/>
<br>
</body>
</html>
Yes, use the jquery append functionality https://api.jquery.com/append/
$('#1').append(html);
Here is a working jsfiddle http://jsfiddle.net/ZqQAu/1/

How to change value of form from drag/drop?

I have a drag and drop feature in my web app, which is shown below. I am trying to get the items that are dragged into the the #contributors div to be placed into a textbox named personalassessment_set3 but I'm not able to do so. Any advice?
form
<p>
<label for="personalassessment_set3">Set3</label><br />
<input id="personalassessment_set3" name="personalassessment[set3]" type="text" />
</p>
<input type="button" value="Set Value" onclick="$('#personalassessment_set3').val( $('#contributors').val() )" />
Drag/drop
<script>
function dragUser(user, event) {
event.dataTransfer.setData('User', user.id);
}
function dropUser(target, event) {
var user = event.dataTransfer.getData('User');
target.appendChild(document.getElementById(user));
}
</script>
<section id="user-levels">
<div id="unassigned" ondrop="dropUser(this, event)" ondragenter="return false" ondragover="return false">
<a draggable="true" class="user" id="leonardo" ondragstart="dragUser(this, event)">Compensation</a>
<a draggable="true" class="user" id="raphael" ondragstart="dragUser(this, event)">Benefits</a>
</div>
<div id="contributors" ondrop="dropUser(this, event)" ondragenter="return false" ondragover="return false">
Ranking
</div>
<div class="clear"></div>
</section>
You are misusing onclick which don't accept any jquery based method or wrapped object.
You should try this instead:
<input id="test" type="button" value="Set Value" />
<script>
$(function(){
$('#test').on('click',function(){
$('#personalassessment_set3').val( $('#contributors').val() )
});
});
</script>

Categories

Resources