I am using this code to show a preview of an image URL.
<input name="input_19" id="input_2_19" type="text" value="" class="medium" placeholder="http://" aria-invalid="false">
<script>
jQuery('#input_2_19').blur(function() {
var src = jQuery(this).val();
var previews = jQuery(".previewImage");
var drawPreview = true;
var PreviousSource = jQuery(this).data('previousSource');
if(!src.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$") && src != "")
{
jQuery("#warning").html("Must be an image");
return false;
} else {
jQuery("#warning").html("");
}
jQuery.each(previews , function(index, value) {
if (src == "" && PreviousSource == $(value).attr('src'))
{
jQuery(value).remove();
drawPreview = false;
return false;
}
if( jQuery(value).attr('src') == src)
{
drawPreview = false;
return false;
}
});
if(drawPreview) {
jQuery('#prev').append('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
}
var previousSource = jQuery(this).data('previousSource', src);
});
</script>
<div id="warning"></div>
<div id="prev"></div>
It works well, but if I change the image URL then the second image will show up too and the first will stay.
How do I make it so only one image preview is shown?
https://jsfiddle.net/LucyTech/qohxryL4/4/
Also why doesn't it work with some images eg
https://ae01.alicdn.com/kf/HTB1q0ucSYrpK1RjSZTEq6AWAVXap/Mifa-Portable-Bluetooth-speaker-Portable-Wireless-Loudspeaker-Sound-System-10W-stereo-Music-surround-Waterproof-Outdoor-Speaker.jpg
what is wrong with this url? In the browser it shows an image so why does the code give an error?
Please use this javascript. That will give you result as per your expectation.
$('#input_2_19').blur(function() {
console.log(jQuery(this).val());
var src = jQuery(this).val();
var previews = $(".previewImage");
var drawPreview = true;
var PreviousSource = $(this).data('previousSource');
if(src.match("/\.(jpeg|jpg|gif|png)$/") != null && src != "")
{
$("#warning").html("Must be an image");
return false;
} else {
$("#warning").html("");
$('#prev').html('<img class="previewImage" style="max-width:50px;" src="' + src + '">');
}
});
Using append() will always add a new element. Maybe you should include the img tag in the initial html with its own id property and change its src property with attr(). You can use show() and hide() on an image element or you can wrap it in a div/span and hide this one.
Before appending the
below code should work.
jQuery('#prev').html('');
After this add your img tag
jQuery('#prev').html('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
The problem of the image not previewing for some the links I think is related to the regular expression that you wrote in the str.math I am not very good in so I can not help you with it but I took a look at your post's first comment "Jinesh", his/her regular expression seems to work. For the other problem, I wrote some piece of code for with comments to fix the the multiple image
// When you release the keyboard key
$("#urlInput").keyup(function(){
$("#warning").text(""); // Clear message div
var url = $("#urlInput").val(); // get url in the input box
if(isValidImageUrl(url)) // Validate the url
$("#prevImg").attr("src", url).show(); // Change src of th eimg tag and Show it
else
$("#prevImg").attr("src", "").hide(); // If the url is not valid, hide the img tag in the html
});
// When you get out the side the input box such as clicking outside or pressing tab key
$("#urlInput").blur(function(){
var url = $("#urlInput").val(); // Get the url in the input box
if(!isValidImageUrl(url)) // Validate the url
$("#warning").text("Must be an image"); // if the url is invalid show warning
});
// Valdiate url fucntion
function isValidImageUrl(checkUrl){
return checkUrl.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,10000}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$");
}
img{
width: 100px;
height: 100px;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="warning"></div>
<input id="urlInput">
<div id="prev">
<img id="prevImg">
</div>
Related
If the word email appears in the URL div id='sociallocker' should show and div id ='emaillocker' should hide.
If the word email is not in the URL: div id='sociallocker' should hide and div id='emaillocker' should show.
So:
URL contains email:
Show div: #sociallocker
Hide div: #emaillocker
URL doesn't contain email:
Show div: #emaillocker
Hide div: #sociallocker
Live link: https://www.moneynest.co.uk/test-page-for-stack/
With the current code both div's are showing regardless?
HTML
<div id="sociallocker">
[sociallocker id="1505"]
</div>
<div id="emaillocker">
[emaillocker]
[/emaillocker]
</div>
JS
<script>
if(document.location.href.indexOf("email") >= 0) {
$("#sociallocker").css(‘display’, ‘none’);
}
</script>
As per my best understanding, I have tried to simulate your question with fake URL string give you an answer.
You have 2 possibilities of hash params either sociallocker or emaillocker and it will show in URL following way #sociallocker or #emaillocker.
As you have tried to do code in core javascript I have given you an answer in core javascript as well.
Here I suppose that you have below url scheme for example.
https://www.moneynest.co.uk/test-page-for-stack/
// When you do in programming uncomment following line.
//var _href = document.location.href;
// When you do in programming comment following line.
var _href= "https://www.moneynest.co.uk/test-page-for-stack/#sociallocker";
var params = _href.split("#")[1];
var divEmailLocker = document.getElementById("emaillocker");
var divSocialLocker = document.getElementById("sociallocker");
if (params.indexOf("sociallocker") > -1) {
divSocialLocker.style.display = "block";
divSocialLocker.style.visibility = "visible";
divEmailLocker.style.display = "none";
divEmailLocker.style.visibility = "hidden";
}else if (params.indexOf("emaillocker") > -1) {
divSocialLocker.style.display = "none";
divSocialLocker.style.visibility = "hidden";
divEmailLocker.style.display = "block";
divEmailLocker.style.visibility = "visible";
}
div#sociallocker, div#emaillocker{
display:none;
}
<div id="sociallocker">
[sociallocker id="1505"]
</div>
<div id="emaillocker">
[emaillocker] [/emaillocker]
</div>
Try this. Use show() and hide() of jQuery.
//str="https://stackoverflow.com/questions/49467845/show-hide-div-dependant-on-url-variable/email";
if(document.location.href.indexOf("email") >= 0) { //insted of 'str' use document.location.href
$("#sociallocker").show();
$("#emaillocker").hide();
}
else{
$("#sociallocker").hide();
$("#emaillocker").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sociallocker">
[sociallocker id="1505"]
</div>
<div id="emaillocker">
[emaillocker]
[/emaillocker]
</div>
try
document.location.href.includes("email")
to check if the word "email" is present in the url
What is the best way to change images based on the last 3 characters on the URL?
I have 3 pictures but when click - needs to stay as the selected image,
but the page refreshes and goes back to original image
<script type="text/javascript">
function image_swap() {
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3)
if (URLChar("NSW"); image.src = "../MCFILES/NSW1.jpg"
if (URLChar("VIC"); image.src = "../MCFILES/VIC1.jpg"
if (URLChar("QLD"); image.src = "../MCFILES/QLD1.jpg"
} else {
image.src = "../MCFILES/NSW1.jpg"
}
}
function newDocNSW() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=NSW");
}
function newDocQLD() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=QLD");
}
function newDocVIC() {
var CurrentURL = window.location.href;
var OriginalURL = CurrentURL.replace(/\&.*/, '');
window.location.assign(OriginalURL + "&St=VIC");
}
</script>
<body>
This is the images i need to change when on hover and when click
runs another script to change URL.
When the page refreshes i need the option to have change picture
when page refreshes to change the URL
<img id="image_swap" src="../MCFILES/NSWO.jpg"
onclick="newDocNSW()"
onmouseover="this.src='../MCFILES/NSW1.jpg';"
onmouseout="this.src='../MCFILES/NSWO.jpg';">
<img id="image_swap" src="../MCFILES/QLDO.jpg"
onclick="newDocQLD()"
onmouseover="this.src='../MCFILES/QLD1.jpg';"
onmouseout="this.src='../MCFILES/QLDO.jpg';">
<img id="image_swap" src="../MCFILES/VICO.jpg"
onclick="newDocVIC()"
onmouseover="this.src='../MCFILES/VIC1.jpg';"
onmouseout="this.src='../MCFILES/VICO.jpg';">
</body>
</html>
This line will only extract a single character
var URLChar = $(location).attr('href').charAt($(location).attr('href').length - 3 )
If you want the last three characters then use this:
var URLChar = $(location).attr('href').substring($(location).attr('href').length - 3, $(location).attr('href').length);
A much simpler plain/vanilla JavaScript approach would be:
var URLChar = location.href.substring(location.href.length - 3, location.href.length);
Your if conditions are also syntactically incorrect. Here's how it should be:
if (URLChar === "NSW"){
image.src = "../MCFILES/NSW1.jpg";
} else if (URLChar === "VIC"){
image.src = "../MCFILES/VIC1.jpg";
} else if (URLChar === "QLD"){
image.src = "../MCFILES/QLD1.jpg";
} else {
image.src = "../MCFILES/NSW1.jpg";
}
I think this should do if I'm understanding the problem correctly.
I wish to change the file upload value when the file name (uploaded file) is too long. For example, if the file name is "This_file_has_a_long_name.txt", I wish to display it with limited characters like "This_file..name.txt".
So I tried the following but it is not working. Please advise.
$("#file_browser").change(function()
{
var filename = this.value;
filename = filename.substr(0,10);
alert(filename);
document.getElementById("file_browse").value = filename;
});
you cant change a property name in js cause of security normaly you will have
a msg SecurityError: The operation is insecure.
if you want you do that you need its to hide the default input file css go to google for that you have tuto
and add your filname custom in a <p></p> for exemple and place where you want
if you really need to change name do that on server side
good day
Try this :
Note:if length of name be 14 and greater , change it.
$(document).ready(function() {
$("#file_browser").change(function() {
var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
//Or for full path use, var filename = $(this).val();
var len = filename.length;
if (len <= 13 ) {
$("#file_browse").text(filename);
}
else {
var part1 = filename.substr(0,5);
var part2 = filename.substr(len - 8);
$("#file_browse").text(part1 + "..." + part2);
}
})
})
<input type="file" id="file_browser">
<p id="file_browse"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
What about some trick.
JS
$("#file_browse").change(function()
{
var data = $(this).val();
$(this).val();
data = data.replace(/(.{1,10}).{1,}(.{6})/,"$1..$2");
$("#file_browse").after("<div style='position:absolute; top:4px; margin-left:230px;'>"+data+"</div>");
});
The add the following css
input[type=file]
{
color:transparent;
}
Adjust the margin-left and top position.
Store the filename into the variable data.
Then make an empty field by using $(this).val(); So your input type file label contain like No file choose are some thing like, this is because of to avoid your input file name is so long means scroll will appear.
Use the pattern replace for include dots.
Then make the div tag for write the filename.
Don't forgot to add the css for transparent file text color.
You better use the name property to get just the file name and hide the default file input because you can't change its value.
$("#fileInput").change(function () {
if (this.files.length === 0) {
return;
}
var name = this.files[0].name;
if (name.length > 14) {
name = name.substr(0, 7) + "..." + name.substr(-7);
}
$("#fileNameText").text(name);
});
$("#chooseButton").click(function () {
$("#fileInput").click();
});
<form>
<input type="file" id="fileInput" style="display: none" />
<button type="button" id="chooseButton">Choose file</button>
<span id="fileNameText">Select a file</span>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a sharepoint webpart I am printing using the script below.
The problem is I need to add a a picture to the header of the page it prints that is located at an address. I am trying to modify this but I don't have alot of javascript experience not sure what the syntax is.
Also I would like to specify the image to a specific size and center it is that possible?
I am aware the src is set to "url" I just don't want to share my actual link on here.
<center>
<input onclick="javascript:void(PrintWebPart())" type="button" value="Print Proof of Pricing"/>
</center>
<script language="JavaScript">
//Controls which Web Part or zone to print
var WebPartElementID = "ctl00_ctl34_g_db6615a7_4c3b_4a14_9bbc_43ce9d63c24d_FormControl0";
var d= new Date();
var elem = document.createElement("img");
elem.setAttribute("src", "url");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Tag");
elem.setAttribute("align", "middle");
//Function to print Web Part
function PrintWebPart()
{
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '<HTML>\n<HEAD>\n';
//Take data from Head Tag
if (document.getElementsByTagName != null)
{
var HeadData= document.getElementsByTagName("HEAD");
if (HeadData.length > 0)
PrintingHTML += HeadData[0].innerHTML;
}
PrintingHTML += '\n</HEAD>\n<BODY>\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML +='<div id="imageDiv">\n</div>\n'
PrintingHTML += WebPartData.innerHTML;
PrintingHTML += "Pricing Date: " +d;
bolWebPartFound = true;
}
else
{
bolWebPartFound = false;
alert ('Cannot Find Web Part');
}
}
PrintingHTML += '\n</BODY>\n</HTML>';
//Open new window to print
if (bolWebPartFound)
{
var PrintingWindow = window.open("","View Proof of Pricing",
"toolbar,width=800,height=600,scrollbars,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
PrintingWindow.document.getElementById("imageDiv").appendChild(elem);
// Open Print Window
}
}
</script>
I believe you can set the image as background to "imageDiv" as
document.getElementById("imageDiv").style["background"]="url(***YOUR_URL***) no-repeat center center";
Note: You do need to give a height to the container as per your need, say
document.getElementById("imageDiv").style["min-height"]="300px";
I am having a problem setting/getting a hidden input's value with JavaScript, and can't see what I'm doing wrong.
What I am basically trying to do is maintain the state of expandable/collapsable divs on my page across form submissions. So I put a hidden input on the page to hold the state of the divs. When a div is expanded/collapsed, I change the value of the input. When the page loads, I read the value of the input and set the state of the divs.
But the value of the input is getting lost. I verify through alerts that it is being set correctly, and then when I read it on load, I verify with an alert that it is empty. Here is the pertinent code:
<input type="hidden" name="ECState" id="hdnECState" />
<script language="javascript" type="text/javascript">
<!--
var ecValue;
function ec(div, btn) {
//expands or collapses an error detail div
var e = document.getElementById(div);
var b = document.getElementById(btn);
var ecStr = div.toString() + ',' + btn.toString() + '|'
if (e.style.display == 'block') {
e.style.display = 'none';
b.src = '../../Images/plus.gif';
ecValue = ecValue.replace(ecStr, '');
}
else {
e.style.display = 'block';
b.src = '../../Images/minus.gif';
ecValue = ecValue + ecStr;
}
alert(ecValue);
document.getElementById('hdnECState').value = ecValue;
}
function reexpand() {
//restores the expanded state of the error detail divs
var pipe, comma, db, div, btn, e, b;
var n = document.getElementById('hdnECState').value;
alert('n=' + n);
if (n != '') {
pipe = n.indexOf('|');
while (pipe > 0) {
db = n.substring(0, pipe);
comma = db.indexOf(',');
if (comma > 0) {
div = db.substring(0, comma);
btn = db.substring(comma + 1);
e = document.getElementById(div);
b = document.getElementById(btn);
e.style.display = 'block';
b.src = '../../Images/minus.gif';
}
n = n.substring(pipe+1);
pipe = n.indexOf('|');
}
}
}
reexpand();
//-->
</script>
When I expand a div, I see the alert from ec() showing that ecValue is 'foo,bar|'.
But after submitting the form, I see the alert from reexpand() saying 'n='.
Anybody see what I'm missing?
You haven't posted Html part of your code. So I am a bit confused, But I think you should put some value first.
<input type="hidden" name="ECState" id="hdnECState" value="1" />
Rudu supplied the answer in a comment, but since I can't mark a comment as the answer, here it is:
I was forgetting that hidden inputs don't automatically keep their value in ViewState across form submissions. I needed to re-value the hidden input on the back end in page load and then everything worked fine.