display image on another window when click select button using Javascript - javascript

Hello there I'm new to the world of Javascript, and I really really need help for school project.
What I want to do, is to display on another windows not only the text with the price, but also the image itself. I tried to add the id on the image and added it to function. Anybody please?
I have this code here in the body element along with other images:
Nike 1
price:$110.99
Size: 9
10
11
<input type= submit value=submit onclick="a()">
This is my script function:
<script>
function a(){
var size ="";
var price = 0;
if(document.getElementById('nike1').checked)
{
price=document.getElementById("nike1").value;
var x =document.getElementById("myimg").src;
}
else if(document.getElementById('nike2').checked)
{
price=document.getElementById('nike2').value;
}
var inputs = document.getElementsByName('r1');
for(var i =0; i<inputs.lenght; i++){
if(inputs[i].checked){
size = inputs[i].value;
}
}
var inputs1 = document.getElementsByName('r2');
for(var i =0; i <inputs1.lenghts;i++){
if(inputs1[i].checked){
size=inputs1[i].value;
}
}
var myWindow = window.open("","MsgWindow","width=200,height=400");
myWindow.document.write("<p><h1>Order Detail</h1> Your ordered Nike shoes<br/> Size:"+size + "<br/>Price:S"+ price + "</p>");
}

Please indent you code for readability. Here it is, a little bit cleaned and with error fixes.
function a() {
var size, price;
if (document.getElementById('nike1').checked) {
price = document.getElementById("nike1").value;
var x = document.getElementById("myimg").src;
} else if (document.getElementById('nike2').checked) {
price = document.getElementById('nike2').value;
}
var inputs = document.getElementsByName('r1');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
size = inputs[i].value;
}
}
var inputs1 = document.getElementsByName('r2');
for (var i = 0; i < inputs1.length; i++) {
if (inputs1[i].checked) {
size = inputs1[i].value;
}
}
var myWindow = window.open("", "MsgWindow", "width=200,height=400");
myWindow.document.write('<p><h1>Order Detail</h1> Your ordered Nike shoes<br/>'+
'<img src="path/to/your/image.png" alt="Nike shoes"></img>'+
'<p>Size: ' + size + '<br/>Price: ' + price + '</p>');
}
To solve your problem, write an img element with a src attribute. Change "path/to/your/image.png" with the real path to the image you want to display.
There were also errors in your code. Your two for loops contained a wrong value: your wrote lenght in the first and lenghts in the second. I fixed it. I tested it and it works. This fiddle is fairly simple and incomplete but shows you the result.

Related

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

Select random number from string of 1's and 0's and change color

I have a string of random 1's and 0's displayed via jQuery. I would now like to select a random number and change it's color. Is it better to work with an array, or a $(div).text() string? I can grab a number from either, but how do I insert it back into the div?
var numbArray = [];
for(i=0; i<10; i++)
{
var randomNumbers = Math.round(Math.random());
$('#numbs').prepend(randomNumbers);
numbArray[i] = randomNumbers;
}
<div id="numbs">0000110111 </div>
The div above is the result of the code, but how do I select a random item, change its color, and display in the original output?
Thanks,
You can locate the number at a certain index, wrap it with the desired color and rebuild the string and set it back to the div using html() and use Math.floor(Math.random() * 10) to generate the random number from zero to the length of the characters you have.
var index = 3;
var originalElementValue;
function colorStringValue(strIndex)
{
strIndex = parseInt(strIndex);
var character = originalElementValue.charAt(strIndex);
$("#numbs").html(originalElementValue.substr(0, strIndex) + "<span style='color:red'>" + character + "</span>" + originalElementValue.substr(strIndex+1));
}
$(document).ready(function(){
originalElementValue = $("#numbs").text();
colorStringValue(index);
$("#strIndex").click(function(){
var rand = Math.floor(Math.random() * 10) + 0 ;
$("#rand").html(rand);
colorStringValue(rand);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="strIndex" > Generate Random Number </button>
<br />
Random Number : <span id="rand"></span>
<br />
<div id="numbs">0000110111</div>
You need to pick a random index from the number string and append some element around that particular number to give it some style.
var number = '0000110111';
var index = Math.floor(Math.random() * number.length);
for(var i = 0; i < number.length; i++) {
var n = number.charAt(i);
if(i == index) {
$('#numbs').append($('<span/>').css('color', 'red').text(n));
} else {
$('#numbs').append(n);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="numbs"></div>
var numbArray = [];
for(i = 0; i< 10; i++) {
var randomNumbers = Math.round(Math.random());
numbArray[i] = randomNumbers;
$('#numbs').prepend(number);
}
var randomNumberSelection = numbArray[Math.floor((Math.random() * (numbArray.length-1)) + 1)];
$('#numbs').html("");
var number;
for(number in numbArray) {
if(number == randomNumberSelection) {
var colorColorCodedNumber = ""+number;
colorColorCodedNumber = colorColorCodedNumber.fontcolor("blue");//blue!
$('#numbs').prepend(colorColorCodedNumber);
} else {
$('#numbs').prepend(number);
}
}
I believe you're looking for something along the lines of this, or at least this is what I took from what you were asking.
In this example be aware you'll see we clear the element then simply reiterate over the array you stored earlier. That is how you 'update' it.
If I understand the question right you want to set a color for a specific position in the div. This means you have to create a span (or another html-element) inside the div at at a random position with a specific color. I havent tested this code below but I guess you could something like this: (in this example red color for the random item)
var randomIndex= Math.floor(Math.random() * 9); //Random number between 0 and 9.
var currentContent = $("#numbs").html();
var randomItem= currentContent.charAt(randomIndex);
newContent = '';
for(i=0; i<10; i++) {
if (i == randomIndex) {
newContent = newContent +
'<span style="background:red;">' + randomItem + '</span>';
}
else {
newContent = newContent + currentContent.charAt(i);
}
}
$("#numbs").html( newContent );
Is this what you are looking for? I just gave it a try. :)
var numbArray = [];
var sample = "<span style='color:#%COLOR%'>%NUM%</span>";
for(i=0; i<10; i++)
{
var randomNumbers = Math.round(Math.random());
var html = sample.replace('%NUM%', randomNumbers);
var randomColor = Math.round((Math.random()* 100000000 )%16777215).toString(16);
html = html.replace('%COLOR%', randomColor);
$('#numbs').prepend(html );
numbArray[i] = randomNumbers;
}
I assumed that you want random colors too.
Good answers by all; thanks! I didn't think of appending the DOM and redisplaying. I went with assigning each number an id and then using css without appending. I was looking for numbers that would turn a color and when all the numbers were that color the script would stop. I don't know which method would perform the best but this way is okay for my limited numbers.
var whiteNumbs =
[0,1,1,0,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,0,0,1,0]
for(var i=0; i<whiteNumbs.length; i++)
{
$("#numbs").append('<span class="white" id="num_' + i + '">' +
whiteNumbs[i] + '</span>');
}
function MakeRed()
{
var randomNumber = Math.floor(Math.random() * whiteNumbs.length-1);
var changeCSS = "#num_" + randomNumber;
$(changeCSS).removeClass('white');
$(changeCSS).addClass("red");
if ($("#numbs span").hasClass("white") )
{
setTimeout(MakeRed,1000);
}
else
{
return false;
}
};
MakeRed();

Star Rating in javascript value comming from backend

I need star rating. In page value are comming from Java/Backend.(I need only javascript or prototypejs solution.)
Eg: If value come 1 then it must show 1 STAR.
If value come 2 then it must show 2 STAR and so on...till 5
This whole thing is happening in dynamic . I am using below code, but this does not create ID.
Javascript
function display() {
var x = "yr";
show_image(x ,2) ;
}
function show_image (id,number) {
var x = number;
var y = id;
for (var i =0; i<x; i++){
var img = document.createElement("img");
img.src = "stars.png";
document.getElementById(y).appendChild(img);
}
}
Thanks for help.
Check this fiddle1 fiddle2
//Just for Demo purpose
function getRating() {
var number = prompt("Enter the rating?");
if(number *= 1 > 0 && number <=5) {
show_image('yr', number);
} else {
alert("Enter valid rating, greater than 0");
}
}
function show_image (id,number) {
document.getElementById(id).innerHTML = '';
for (var i =0; i<number; i++){
var img = document.createElement("img");
img.height=10;
img.src = "http://icons.iconarchive.com/icons/custom-icon-design/flatastic-2/512/star-full-icon.png";
document.getElementById(id).appendChild(img);
}
}
Your code has no issue, it is working fine. Simplest way to call this function from your Java Servlet/JSP response is, added <script>show_image('_some_id_', number_of_star)</script>
Add comment, if you have any query, or if my understanding of problem itself is not correct.

Can we get radiobuttonList.Items.Count in .aspx page

Can we get the count of total radiobuttonlist items from .aspx page. I have to call a javascript function onclientclick of a button and i want to loop through the total number of radiobuttonlist items. So can anyone tell me that can we get it from .aspx page. Because in my scenario i can not use code behind for this.
function ClearRBL() {
for (i = 0; i < RBLCOUNT; i++) {
document.getElementById('rblWorkerList_' + [i]).checked = false;
}
}
How can i get RBLCOUNT here from .aspx page only? If not possible then in Javascript please.
I don't know how the aspx side would work, but if you want to do it just in JavaScript you could do something like the following that doesn't need to know the total number of elements in advance:
function ClearRBL() {
var i = 0,
rbl;
while (null != (rbl = document.getElementById('rblWorkerList_' + i++)))
rbl.checked = false;
}
The above assumes that the element ids end in numbers beginning with 0 counting up by 1s; the while loop will keep going until document.getElementById() doesn't find a matching element (in which case it returns null). A less cryptic way of writing it is as follows:
function ClearRBL() {
var i = 0,
rbl = document.getElementById('rblWorkerList_' + i);
while (null != rbl) {
rbl.checked = false;
i++;
rbl = document.getElementById('rblWorkerList_' + i);
}
}
P.S. When the while loop finishes i will be equal to the number of radio buttons, which may be useful if you want to do something with that number afterwards.
Try this:- This is not exactly what you want but hope it will help you.
function GetRBLSelectionID(RadioButtonListID) {
var RB1 = document.getElementById(RadioButtonListID);
var radio = RB1.getElementsByTagName("input");
var isChecked = false;
var retVal = "";
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
retVal = radio[i].id;
break;
}
}
return retVal;
}
you can give a name all radio button and then get them like this.
var RBLCOUNT= document[groupName].length;
or
var RBLCOUNT= 0;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
if(inputs[i].type =="radio"){
RBLCOUNT++;
}
}
I just created a javascript function as mentioned by Karthik Harve and found the total number of rows generated dynamically as below: -
function ClearRBL() {
var rblLen = document.getElementById('rblWorkerList');
for (i = 0; i < rblLen.rows.length; i++) {
document.getElementById('rblWorkerList_' + [i]).checked = false;
}
}
It's working on both Mozila and IE.
Thanks alot to all who tried to help.

Pre-formatting text to prevent reflowing

I've written a fairly simple script that will take elements (in this case, <p> elements are the main concern) and type their contents out like a typewriter, one by one.
The problem is that as it types, when it reaches the edge of the container mid-word, it reflows the text and jumps to the next line (like word wrap in any text editor).
This is, of course, expected behavior; however, I would like to pre-format the text so that this does not happen.
I figure that inserting <br> before the word that will wrap would be the best solution, but I'm not quite sure what the best way to go about doing that is that supports all font sizes and container widths, while also keeping any HTML tags intact.
I figure something involving a hidden <span> element, adding text to it gradually and checking its width against the container width might be on the right track, but I'm not quite sure how to actually put this together. Any help or suggestions on better methods would be appreciated.
Edit:
I've managed to write something that sort of works using jQuery, although it's very sloppy, and more importantly, sometimes it seems to skip words, and I can't figure out why. #content is the name of the container, and #ruler is the name of the hidden <span>. I'm sure there's a much better way to do this.
function formatText(html) {
var textArray = html.split(" ");
var assembledLine = "";
var finalArray = new Array();
var lastI = 0;
var firstLine = true;
for(i = 0; i <= textArray.length; i++) {
assembledLine = assembledLine + " " + textArray[i];
$('#ruler').html(assembledLine);
var lineWidth = $('#ruler').width();
if ((lineWidth >= $('#content').width()) || (i == textArray.length)) {
if (firstLine) { var tempArray = textArray.slice(lastI, i); }
else { var tempArray = textArray.slice(lastI+1, i); }
var finalLine = tempArray.join(" ");
finalArray.push(finalLine);
assembledLine = "";
if (lineWidth > $('#content').width()) { i = i-1; }
lastI = i;
firstLine = false;
}
}
return finalArray.join("<br>");
}
You could use the pre tag: Which displays pre-formatted text, or you could put the content into a div tag, set a fixed width, and script based upon that.
The best way (IMO) would be to add the whole word, but have the un-"typed" letters invisible. E.g:
H<span style="visibility: hidden;">ello</span>
He<span style="visibility: hidden;">llo</span>
Hel<span style="visibility: hidden;">lo</span>
Hell<span style="visibility: hidden;">o</span>
Hello
To make it easier, give the span a name, and delete it from the DOM each time.
A possible approach is to set p display inline (because default display-block will make p to consume all width even if it has just 1 character) and then as you 'type' check the element width.
Set a tolerance in px (25px for example) and once p's width reaches total available width minus width tolerance you insert <br />
I think this should work...
After playing with the code I edited into the question, I managed to get it working decently.
Code:
function formatText(html) {
var textArray = html.split(" ");
var assembledLine = "";
var finalArray = new Array();
var lastI = 0;
var firstLine = true;
for(i = 0; i <= textArray.length; i++) {
assembledLine = assembledLine + " " + textArray[i];
$('#ruler').html(assembledLine);
var lineWidth = $('#ruler').width();
if ((lineWidth >= $('#content').width()) || (i == textArray.length)) {
if (firstLine) { var tempArray = textArray.slice(lastI, i); }
else { var tempArray = textArray.slice(lastI+1, i); }
var finalLine = tempArray.join(" ");
finalArray.push(finalLine);
assembledLine = "";
if (lineWidth >= $('#content').width()) { i = i-1; }
lastI = i;
firstLine = false;
}
}
return finalArray.join("<br>");
}
Not perfect, but it'll do. Thanks, everyone.

Categories