I have a list box with id of 'availmap' containing filename of images the path is maps/image.jpg
I also have a image control with id of 'map' that I would like to change to the selected image using the onclick event of the list box
this is the js I have tried and can not figure out why it won't work
<script type="text/javascript">
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.src="maps/" + img;
}
This is the image tag and the listbox code
<div id='avail' style='position:fixed;left:500px;top:0;z-index:0;text-align:center;bgcolor='#00b0e6';>
<span style='position:fixed;left:540px;top:30px;width:250px;font-family:Arial;font-size:15px;background-color:#00b0e6;border: 1px #000000 solid;'>Availible Maps</span> </div>
<form action='jobs.php' target='joblist' style='position:fixed;left:500px;top:101px;'></td>
<select id='availmap' name='availmap' size='10' style='width: 250px;position:fixed;left:540px;top:51px;' onchange='ChgImg()'>
EOY;
while($row = mysqli_fetch_array($mapresult))
{
echo "<option value=\"".$row['ID']."\">".$row['AssocMap']."</option>\n ";
}
echo "</select>";
echo "</form>";
echo "<img id='map' src='' alt='' style='position:absolute;left:800px;top:30px;width:260px;height:185px;border: 1px #000000 solid;'>";
I'm sure it is something relatively simple I am missing here
You should use Element.setAttribute()
Adds a new attribute or changes the value of an existing attribute on
the specified element.
element.setAttribute(name, value);
Params
name is the name of the attribute as a string.
value is the desired new value of the attribute.
So, change your code to this:
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.setAttribute("src", img);
You're javascript was almost correct, just use id.src=img;
Complete javascript:
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.src=img;
}
I would use the change event instead of the click event. Don't forget to add the code in the head of the page.
UPDATE
The javascript you're using works fine as you can see in the working example. However, I don't think you're passing a valid value for the src of the image in the code you provide (value=\"".$row['ID']."\). It seems you're using the ID of the row for the value (usually a number) when you actually need to use a valid src for the image (for example http://www.w3schools.com/images/w3schools_green.jpg). Do you have the url of the images stored in some other column of the row? If so, use it instead of $row['ID']
Also, please check your HTML. There are a few mistakes that you should correct (most of them single quotes badly closed).
I've also modified your html a bit in the example
Related
I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.
I retrieve image paths with the function get_all();. This get_all function retrieves images as an object. This object has the attributes name, source_path and date. I want my javascript to add images to a div. I have the following:
The instantiate.php includes files like Jquery and another JS file.
<?php
require_once("../../include/instantiate.php");
$photos = Photos::get_all();
$JSPhotos;
foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($JSPhotos); ?>;
for(var i = 0; i <= 10; i++)
{
create_image("../"+photos[i]);
}
});
This does not work. Anyone got a solution?
Solution in Jeroen's Post!
New Problem;
In the create_image function I set the class and src of the image element. When you click such an image I want an alert box to show up. I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". So, any idea why this dont work?
Script in the javascript part:
$(".imgid").click(function() {
alert("hey");
});
You are not assigning anything to your variable.
You probably want:
$JSPhotos = array();
foreach($photos as $photo) {
$JSPhotos[] = $photo->source_path;
}
Or something similar.
Am trying to find if the ID is present in a variable which has HTML content.
ID name is getting attached to DIV element by dynamic variables.
strHTML = "<div id='"+var1+var2+"'>"
Now, i like to check if a particular ID is present in strHTML.
How do i do that.?
Thanks in advance.
EDITED
Added actual code for more clarity...
for(data in ArrayOFObjects)
var splitDate = ArrayOFObjects[data]["NewsDate"].split("-");
**if(!$(strHTML).find('#'+splitDate[1]+splitDate[0]))** // if condition is not correct, just my try
{
strHTML += "<div id='"+splitDate[1]+splitDate[0]+"></div>"
}
}
So when the next for in loop happens, i like to check if the ID already exist in strHTML, if it exists then i do not want the DIV creation to happen
Thanks
If you want to know if your HTML contains an element whose id contains some value, you may do
var $elements = $('[id~="'+someValue+'"]', '<div>'+strHTML+'</div>');
var doContain = $elements.length>0;
If your string strHTML is really something like "<div id='"+var1+var2+"'>", then simply use a regex :
var id = strHTML.match(/["']([^\"']*)["']/)[1];
and look in id for your id.
You can use javaScript's search function:
var n=strHTML.search(var1+var2);
if (n > -1)
{
// found it!
}
hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.
i have a table such that each row is like this
<tr>
<td><input/> <img id="foo" src="redMinus.png"/></td>
some more tds
<td> <a onclick="wow('foo',$(this))"></a>
</tr>
I want to find out if the img in the first td has an src that contains "redMinus"
This is what I have but it doesnt seem to be working?
function wow(id, item){
var tr$ = item.parentNode.parentNode;
var details = tr$.find('img[src*="redMinus"]');
}
Any ideas?
Thanks!
You're mixing jQuery with DOM elements.
Change your code to
var details = item.closest("tr").find('img[src*="redMinus"]');
Your parameter is given the name item within your function, but you are trying to use a variable with the name item$ instead. Either rename the parameter or use the correct parameter name in the function.
var same = "redMinus" == $(this).parent('td').prev().children('img').attr('src').substring(0,7);
function wow(id, item){
var src = $('#' + id).attr('src');
var srcIndex = src.indexOf('redMinus');
if(srcIndex >= 0)
// redMinus is present in the string
else
// redMinus is not present in the string
}