How would I dynamically update the end part of an img URL based on a drop down selection?
for example when blue is selected the filename before .jog would get filled in with the word blue. It's using a css and I can't add any ids to the :
<img src="www.mysite.com/blue.jpg">
<select>
<option>green</option>
<option>blue</option>
</select>
$(document).ready(function() {
$('select').change(function(){
var src = $(':selected', this).text()
$('img').attr('src', location.hostname + "/" + src + '.jpg');
});
});
$(function () {
$('select').change(function () {
$(this).parent().attr('src', location.hostname + "/" + this.val() + '.jpg');
});
});
Try this:
$(function() {
var $img = $('img'), $select = $('select').on('change keyup', function() {
$img.attr('src','http://www.mysite.com/' + $select.find(':selected').html() + '.jpg')'
});
});
Related
I use a captcha in my login form and I want to refresh the captcha when I click the captcha itself!but it doesn't work!
my html code:
<cite class="fr">
<img id="captcha_img" src="securimage/securimage_show.php" alt="点击图片刷新验证码" />
</cite>
my jquery code:
$('#captcha_img').click(function(){
//alert("hh");
$('#captcha_img').attr("src","securimage/securimage_show.php");
});
I also search some docs about this question and try some other ways,but it still doesn't work,can someone give me some ideas?
Both methods below should work ( uncomment one by one and try it ):
jQuery(function ($) {
$('#captcha_img').on( 'click', function() {
// $(this).attr( "src","securimage/securimage_show.php?"+Math.random() );
// $(this).attr( "src","securimage/securimage_show.php?"+new Date().getTime() );
});
});
Browser is probably caching image. Try this:
$('#captcha_img').click(function() {
var imageUrl = 'securimage/securimage_show.php?' + new Date().getTime();
$(this).attr('src', imageUrl);
});
DEMO
$(function () {
$('#foo').click(swapImages);
var secondImg = 'http://digital-photography-school.com/wp-content/uploads/2013/03/Acorn256.png';
function swapImages() {
var img = $("<img id='foo' src='" + secondImg + "' />");
$(this).replaceWith(img);
$(img).click(swapImages);
}
});
$('#captcha_img').click(function(){
//alert("hh");
$('#captcha_img').attr("src","securimage/securimage_show.php");
return false;
});
Or use e.preventDefault() like
$('#captcha_img').click(function(e){
e.preventDefault();
$('#captcha_img').attr("src","securimage/securimage_show.php");
//return false;
});
tell me if that works. In this case, return false will work just fine because the event doesn't need to be propagated.
I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.
The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.
Here're the problems I'm facing:
If a dropdown/input hasn't been touched, I want to leave it out of the URL.
If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").
Here's the code for the jQuery:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url += "&type="+$(this).val();
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
Here's the code where I load the image:
<div id="loadsignature">
<div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>
I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.
Thank you for your help!
EDIT:
Here's the current code:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
function updateQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re))
{
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else
{
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
</script>
EDIT2:
Here's the code for signatureload.php
<?php
$url = "signature.php?";
$count = 0;
foreach($_GET as $key => $value)
{
if($count > 0) $url .= "&";
$url .= "{$key}={$value}";
}
echo "<img src='{$url}'></img>";
?>
If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.
This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re)) {
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
$('#signature_type').change(function () {
// Update the type param using said function
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
Here is a variant where all the data is keept in a separate javascript array
<script>
var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
var urlparams = {};
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
urlparams['type'] = $(this).val();
LoadSignature();
});
function LoadSignature()
{
var gurl = baseurl; // there is always a ? so don't care about that.
for (key in urlparams) {
gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
}
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(gurl, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
With this color or any other parameter could be added with urlparams['color'] = $(this).val();
Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example
var type= 'default_value';
$("#signature_type").change(function() {
type = $(this).val();
});
then using ajax call it like this (you could do this in your "change" event function):
$.ajax({
type: 'GET',
url: 'signatureload.php',
data: {
user: <?php echo $_SESSION['sess_id']; ?>,
type: type,
... put other variables here ...
},
success: function(answer){
//load image to div here
}
});
Maybe something like this:
<script>
var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(function(){
LoadSignature(baseUrl);
}, 1500);
});
$("#signature_type").change(function() {
var urlWithSelectedType = baseUrl + "&type="+$(this).val();
LoadSignature(urlWithSelectedType);
});
function LoadSignature(urlToLoad)
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(urlToLoad, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
I used MooDialog.iframe and onClose i need some values. But not able to fetch values from that iFrame and want to use in the page i opened this frame in popup.
The function/code i used for popup is below:
function popup_window() {
var hostname = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
var opcion = "crear";
co2=new MooDialog.IFrame(hostname+'infinity/contabilidad/cuenta%20crear/popup_window.php?action=2',
{
title: 'Editar Centro','class' : 'content_edit1 MooDialog',
onClose: function()
{
/////////alert(document.getElementById('numero_cuenta').value);
//numero_cuenta is something i want
location.reload();
}
}
);
}
numero_cuenta is the id of the input.text of the popup iframe.
I found the solution:
From the popup_window.php file get the element by id via frame. We need to use the following code:
onClose: function()
{
var myIFrame = document.getElementById("MooFrame");
var content = myIFrame.contentWindow.document.getElementById('abcd').value;
alert('content: ' + content);
location.reload();
}
I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.
My project is in PHP / MySQL. I'm using Smarty for a template engine.
I have a < select > tag in my smarty file:
maps.tpl -
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="maps.php">
<td colspan="3">
<select id="cmdview" name="cmd">
<option value=""></option>
<option value="commdata" {if $cmdOn == "commdata"}selected="true"{/if}>Communications</option>
<option value="contacts" {if $cmdOn == "contacts"}selected="true"{/if}>Contacts</option>
<option value="enrollment" {if $cmdOn == "enrollment"}selected="true"{/if}>Enrollment</option>
<option value="all" {if $cmdOn == "all"}selected="true"{/if}>All Schools</option>
</select>
<input type="submit" name="doSwitch" value="Submit" />
</td>
<div id="append"></div2>
</form>
So far, my jQuery code finds which value is selected:
{literal}
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$('#append').text(str);
})
.change();
</script>
{/literal}
I need the jQuery to listen for the value of "cmdview" then post that value to file: maps_append.php . I need that file to .append/.change the current file (maps.php/maps.tpl) without reloading.
But, my jQuery is only half working. The jQuery does find the value I'm trying to pass, and I've gotten it to load that correct value in the <.d.i.v.> tag with id #append . The only thing I can't seem to do is that take value and actually post it to maps_append.php
Any help will be very appreciated!
Thank you!
PS: I think the change will be something like this:
This needs to be replaced:
$('#append').text(str);
})
.change();
With something like this:
url = "maps_append.php";
$.post( url, { cmd: cmdview, value: str } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
$term_input.val('');
});
EDIT::
My current file is maps.php. I now have it appending maps_append.php to maps.php with this code:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$('#append').load(url);
})
.change();
</script>
I just need to post the value of the select tag now!
Closer still... please see this edit:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post( url, { str: "$cmdOn" } ,
function( data ) {
var content = $( data );
$('#append').load(url);
})
.change();
});
</script>
Now the maps_append.php page only appends to maps.php when I change the value of the select tag. I only need to include the value of the select tag when maps_append.php appears now.
I don't quite understand the details of what you are doing here -- all the code looks fine but the plan seems a little strange.
Typically you don't have a program change the source. Instead you would have code store data in a database and the code would be driven by the database to produce different output.
Maybe this is what you want to do with the content -- store it in a database and have a page that displays it.
To load content via jQuery use the following
function loadContent(elementSelector, sourceUrl) {
$(""+elementSelector+"").load("http://yoursite.com/"+sourceURL+"");
}
See this link: http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html