Replace Variable in URL onClick - javascript

Want to replace the varaible after 'sku=' in the src= using onClick, then reload the iframe.
<iframe id="preview" src="//preview.domain.com/?sku=100-1&month=May"></iframe>
<div class="smr-three">
<button id="smrone" onclick="smrclickone()">test1</button>
<button id="smrtwo" onclick="smrclicktwo()">test2</button>
<button id="smrthree" onclick="smrclickthree()">test3</button>
<script>
function('smrclickone') {
document.getElementById('preview').src = document.getElementById('preview').src.replace('sku','100-1')
};
function('smrclicktwo') {
document.getElementById('preview').src = document.getElementById('preview').src.replace('sku','100-2')
};
function('smrclickthree') {
document.getElementById('preview').src = document.getElementById('preview').src.replace('sku','100-3')
};
</script>

This is simpler:
var baseUrl = "//preview.domain.com/?month=May";
window.onload=function() {
document.querySelector(".smr-three").onclick=function(e) {
if (e.target.tagName=="BUTTON") {
document.getElementById('preview').src = baseUrl+"&sku="+this.getAttribute("data-sku");
}
}
}
using
<iframe id="preview" src="//preview.domain.com/?sku=100-1&month=May"></iframe>
<div class="smr-three">
<button type="button" id="smrone" data-sku="100-1">test1</button>
<button type="button" id="smrtwo" data-sku="100-2">test2</button>
<button type="button" id="smrthree" data-sku="100-3">test3</button>
</div>

Replace does not do what you think here. This function can be used to update GET parameters in a URL:
function updateURLParameter(url, param, paramVal) {
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
Use that on your URL the following way:
let preview = document.getElementById('preview')
function smrclickone() {
preview.src = updateURLParameter(preview.src, "sku", "100-1");
console.log(preview.src)
};
function smrclicktwo() {
preview.src = updateURLParameter(preview.src, "sku", "100-2");
console.log(preview.src)
};
function smrclickthree() {
preview.src = updateURLParameter(preview.src, "sku", "100-3");
console.log(preview.src)
};
function updateURLParameter(url, param, paramVal) {
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i = 0; i < tempArray.length; i++) {
if (tempArray[i].split('=')[0] != param) {
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
<iframe id="preview" src="//preview.domain.com/?sku=100-1&month=May"></iframe>
<div class="smr-three">
<button id="smrone" onclick="smrclickone()">test1</button>
<button id="smrtwo" onclick="smrclicktwo()">test2</button>
<button id="smrthree" onclick="smrclickthree()">test3</button>

Related

getting the variable's value from another funtion

Is there a way to get the 'username' and 'questionid' variable's value in my send() function like how I did with inputText?
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
var username = data[0].username;
//var examid = data[1].examid;
var questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
You do not need var before username and questionid in your renderHTML function, as they have already been defined:
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
username = data[0].username;
//var examid = data[1].examid;
questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);

Overwrite existing URL parameter value with new

I want this code to replace an existing URL parameter "aspid", but what it does is adding an another id on the existing one. Can anyone help?
$(document).ready(function() {
function GetUrlValue(VarSearch) {
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for (var i = 0; i < VariableArray.length; i++) {
var KeyValuePair = VariableArray[i].split('=');
if (KeyValuePair[0] == VarSearch) {
return KeyValuePair[1];
}
}
}
var asid = GetUrlValue('aspid');
var campaign = GetUrlValue('utm_campaign');
if (asid != undefined) {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&aspid=" + asid : "?aspid=" + asid);
});
}
});
You need to call this function on every a:
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
And call the function like so:
updateURLParameter(window.location.href, 'paramName', 'Value')
complete code be like :
...
$("a").attr('href', function(i, h) {
if(h){
return updateURLParameter(h, 'aspid', asid);
}
});
...

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

image upload not working when changing upload button from input to span

I have the following image upload script:
function upload_media_async(form_name, media_type, file_path, file_url, file_embed, nb_uploads, max_uploads, upload_id) {
var radio_buttons = [];
for (var i = 0; i < form_name.length; i++) {
if (form_name.elements[i].type == 'radio' && form_name.elements[i].checked == true) {
radio_buttons[form_name.elements[i].name] = form_name.elements[i].value;
}
}
var jsHttp = new JsHttpRequest();
var xmlHttp = GetXmlHttpObject();
if (jsHttp == null) {
alert("Browser does not support HTTP Request");
return;
}
var media_name = '';
switch (media_type) {
case 1:
media_name = 'ad_image';
break;
case 2:
media_name = 'ad_video';
break;
case 3:
media_name = 'ad_dd';
break;
}
var media_box_name = 'display_media_boxes_' + media_name;
file_embed = base64Encode(file_embed);
var url = relative_path + 'ajax_files/upload_file.php';
var action = url + '?do=add&media_type=' + media_type + '&file_url=' + file_url +
'&file_embed=' + file_embed + '&nb_uploads=' + nb_uploads + '&upload_id=' + upload_id;
var thumbnail_div = document.getElementById('display_media_boxes_' + media_name);
var new_content = document.createElement('div');
if (file_embed != '') {
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
var results = response.split('|');
if (results[5] != '') {
alert(results[5]);
}
else {
new_content.innerHTML = results[3];
while (new_content.firstChild) {
thumbnail_div.appendChild(new_content.firstChild);
}
var hidden_div = document.getElementById('hidden_media_boxes');
var hidden_content = document.createElement('div');
hidden_content.innerHTML = '<input type="hidden" name="' + results[1] + '[]" id="hidden_' + results[2] + '" value="' + results[4] + '">';
while (hidden_content.firstChild) {
hidden_div.appendChild(hidden_content.firstChild);
}
nb_uploads++;
}
// document.getElementById('div_file_' + media_type).innerHTML = document.getElementById('div_file_' + media_type).innerHTML;
document.getElementById('item_file_url_' + media_type).value = '';
document.getElementById('item_file_embed_' + media_type).value = '';
if (nb_uploads >= max_uploads) {
document.getElementById('btn_upload_' + media_type).disabled = true;
document.getElementById('item_file_upload_' + media_type).disabled = true;
document.getElementById('item_file_url_' + media_type).disabled = true;
document.getElementById('item_file_embed_' + media_type).disabled = true;
}
document.getElementById('nb_uploads_' + media_type).value = nb_uploads;
}
};
xmlHttp.open("POST", action, true);
xmlHttp.send(null);
}
else {
jQuery.blockUI({message: '<p style="padding: 10px; font-size: 16px; font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold;">' + upl_progress_msg + '</p>'});
var image_loading = document.createElement('div');
image_loading.innerHTML = '<img src="' + relative_path + 'images/loading-media.gif">';
thumbnail_div.appendChild(image_loading);
jsHttp.onreadystatechange = function() {
if (jsHttp.readyState == 4) {
var response = jsHttp.responseText;
var results = response.split('|');
if (results[5] != '') {
alert(results[5]);
thumbnail_div.removeChild(image_loading);
setTimeout(jQuery.unblockUI, 500);
}
else {
new_content.innerHTML = results[3];
while (new_content.firstChild) {
thumbnail_div.replaceChild(new_content.firstChild, image_loading);
}
setTimeout(jQuery.unblockUI, 500);
var hidden_div = document.getElementById('hidden_media_boxes');
var hidden_content = document.createElement('div');
hidden_content.innerHTML = '<input type="hidden" name="' + results[1] + '[]" id="hidden_' + results[2] + '" value="' + results[4] + '">';
while (hidden_content.firstChild) {
hidden_div.appendChild(hidden_content.firstChild);
}
nb_uploads++;
}
// document.getElementById('div_file_' + media_type).innerHTML = document.getElementById('div_file_' + media_type).innerHTML;
document.getElementById('item_file_url_' + media_type).value = '';
document.getElementById('item_file_embed_' + media_type).value = '';
if (nb_uploads >= max_uploads) {
document.getElementById('btn_upload_' + media_type).disabled = true;
document.getElementById('item_file_upload_' + media_type).disabled = true;
document.getElementById('item_file_url_' + media_type).disabled = true;
document.getElementById('item_file_embed_' + media_type).disabled = true;
}
document.getElementById('nb_uploads_' + media_type).value = nb_uploads;
for (var i = 0; i < form_name.length; i++) {
if (form_name.elements[i].type == 'radio' && radio_buttons[form_name.elements[i].name] == form_name.elements[i].value) {
form_name.elements[i].checked = true;
}
}
}
};
jsHttp.open("POST", action, true);
jsHttp.send({file: file_path});
}
}
This works fine when using this HTML:
<div id="div_file_1">
<input name="item_file_upload_1" id="item_file_upload_1" style="width: 250px;"
onchange="upload_media_async(ad_create_form, 1,
this.form.item_file_upload_1,
document.getElementById('item_file_url_1').value,
document.getElementById('item_file_embed_1').value,
document.getElementById('nb_uploads_1').value,
5,
'A_571');" type="file">
</div>
Now, I am wrapping the INPUT in a SPAN in order to style it:
<div id="div_file_1">
<span class="btn btn-file" name="item_file_upload_1"
id="item_file_upload_1" style="width: 250px;"
onchange="upload_media_async(ad_create_form, 1,
this.form.item_file_upload_1,
document.getElementById('item_file_url_1').value,
document.getElementById('item_file_embed_1').value,
document.getElementById('nb_uploads_1').value,
5,
'A_571');">
<input type="file">
</span>
</div>
And suddenly the upload doesn't work anymore. When I click to select a file, it does nothing ...it just sits there. What do I have to change in order to make it work even with the SPAN wrapped around the INPUT?
In this.form.item_file_upload_1, this refers to the span. Therefore this.form is undefined. We need to access the form another way. You'll also need to move the name and id back to their <input>. That should get you on the right path.

Reload a page with additional data

If I have the following:
http://www.domain.com/myscript?x1=v1&x2=v2
And I would like to reload this page with additional data {x3: v3, x4: v4}. What is the simple way to do without manipulating the original url?
Reload the page using window.location
var original_url = window.location;
window.location = original_url + "&x3=data3&x4=data4";
Edit: You can update values from url using this function:
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
You can use it:
var x1 = updateURLParameter(window.location.href, 'x1', 'updatedData1');
var url = updateURLParameter(x1, 'x2', 'updatedData2');
window.location = url;

Categories