Adding a parameter to URL with checkbox (jQuery) - javascript

I'm adding ?show={COUNTRY CODE} to URL as a parameter. I managed to add it with the code below but can't remove it when you unselect the checkbox.
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results) {
return results[1];
} else {
return 0;
}
}
$('#uc').click(function() {
var country = $(this).val();
var site_url = $('body').data('site-url');
var url = $('body').data('url');
window.location.href = site_url + url + '?show=' + country;
});
if ($.urlParam('show') == $('#uc').val()) {
$('#uc').attr('checked', true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="uc" id="uc" value="UK"> <label for="uc">Only UK</label>

Use the condition to check the checkbox is clicked or not.
if ($(this).is(':checked')) {
console.log(site_url + url + '?show=' + country)
} else {
console.log(site_url + url)
}

Use change() not click() then check with .is(':checked')
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results) {
return results[1];
} else {
return 0;
}
}
$('#uc').change(function() {
var country = $(this).val();
var site_url = $('body').data('site-url');
var url = $('body').data('url');
var site_url = 'google.com' // temp remove later
var url = '/sd/' // temp remove later
if ($(this).is(':checked')) {
console.log(site_url + url + '?show=' + country)
//window.location.href = site_url + url + '?show=' + country; // uncomment later
} else {
console.log(site_url)
//window.location.href = site_url; // uncomment later
}
});
if ($.urlParam('show') == $('#uc').val()) {
$('#uc').attr('checked', true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="uc" id="uc" value="UK"> <label for="uc">Only UK</label>

Related

Javascript window relocating adding unwanted parameter

I've been trying this for a lot of time now. I'm getting a value with the input and I'm trying to redirect the page by adding a new parameter and just passing dummy value 23 for now to the parameter number_range.
However, in the end in the window.location part it adds the parameter myurl/?e=1 always at the start. After that it redirects properly. How do I fix this. Please Help.
Also I'm new to javascript so please forgive my bad code and possible mistakes.
<h3>Price Filter</h3>
<input id="number_range" type="text"/><br>
<button onclick="filter_start(this,'gt'); return true;">Greater or equal</button><br>
<button onclick="filter_start(this,'ltt'); return false;">Less or equal</button>
<script language="javascript" type="text/javascript">
var filter_start = function(el, indicator){
setGetParameter("number_range", 23);
}
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0)
{
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?")+1) + params.join("&");
}
else
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
EDIT: Sorry just ran it in another place and this seems to work. I Think the problem then lies in Django's admin template or jquery.
Seems that you're missing some curly bracers. I've tidied your code very slightly:
var filter_start = function(el, indicator) {
setGetParameter("number_range", 23);
}
function setGetParameter(paramName, paramValue) {
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0) {
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?") + 1) + params.join("&");
} else {
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
}

Unexpected token } can not find the mistake

i tried everything but i don't know where the mistake should be its show me a unespekted token } in a line where i not even have this sign.
<script type="text/javascript">
function postToStatus(action,type,user,ta){
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ><br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+
'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_'+sid+
'"><a href="#" onclick="return false" >onmousedown="deleteStatus("'+sid+
'\',\'status_'+sid+
'\');" title="DELETE THIS STATUS AND ITS REPLIES">delete status</a> ></span><br />'+data+
'</div></div>"'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
}
You need to put a semi-colon after the last } just before the ajax.send() call.
This website is your best friend if you write JavaScript: http://closure-compiler.appspot.com/home
function postToStatus(action, type, user, ta) {
var data = _(ta).value;
if (data == "") {
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if (datArray[0] == "post_ok") {
var sid = datArray[1];
data = data.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, " ><br />").replace(/\r/g, "<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_' + sid + 'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_' + sid + '">delete status ></span><br />' + data + '</div></div>"' + currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
};
ajax.send("action=" + action + "&type=" + type + "&user=" + user + "&data=" + data);
}
;

YouTube ajax, .replace() not working

I Am using the jquery below and witht he addition of .replace(",", " ") to the var video_tags=data.tags doesn't return a value. how can i replace the commas with spaces.
http://jsfiddle.net/hJGe4/1/
$(document).ready(function () {
$(".search_input").focus();
$(".search_input").keyup(function () {
$("#video").html('');
var search_input = $(this).val();
var keyword = encodeURIComponent(search_input);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=6&v=2&alt=jsonc';
$.ajax({
type : "GET",
url : yt_url,
dataType : "jsonp",
success : function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_title = data.title;
var video_tags = data.tags.replace(",", " ");
var final = video_title + '<br/>' + video_tags + '<br/><br/><br/>';
$("#video").append(final);
});
} else {
$("#video").html("<div id='no'>No Video</div>");
}
}
});
});
});
var video_tags=data.tags.replace(",", " ");
should be
var video_tags=data.tags.join(" ");
DEMO

Jquery ajax Check if there results are empty

I am using the following code to pull in data from my database and plot points with google maps. What I want to do is something like, "if response=null, alert('empty')" but everytime I try to work that into this code, something just breaks. If anyone could offer any help that would be awesome.
Here is my code:
<script type="text/javascript">
$(function ()
{
var radius3 = localStorage.getItem("radius2");
var lat3 = localStorage.getItem("lat2");
var long3 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var citya = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://examplecom/test/www/base_search.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
if (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
} else {
alert('hello');
}
}
})
}
});
})
}
</script>
Something like
success: function (data) {
if(!data) {
alert('empty');
return;
}
$.each(data, function (key, val) { ...
should work.
Something like this!
success: function (data) {
if(data.length == 0) {
alert('empty');
return;
}
Something like this?
success: function (data) {
if(data){
//do your stuff here
}
else{
alert('empty');
}
}

jquery javascript problem

Could you please take a look and tell why this isnt working i cant figure it out. the problem is with
$("#item_name").val(item_name);
$("#amount").val(course_price);
This should be adding info to 2 hidden inputs (
<input type="hidden" name="item_name" id="item_name"value="">
<input type="hidden" name="amount" id="amount" value="">
)
but they are coming up as blank
also the value from course_name.php?courseID=1 is Course Name,500
Full Javascript
<script>
$(document).ready(function() {
url = "date_range.php?courseID="+$('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID="+$('#course_name').val();
var course_details;
$.get(url, function(data){
course_details= data;
});
split_course_details = course_details.split(',');
course_name=split_course_details[0];
course_price=split_course_details[1];
course_date=$("#date_range").val();
item_name=course_name+' - '+course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
$('#course_name').change(function() {
url = "date_range.php?courseID="+$('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID="+$('#course_name').val();
var course_details;
$.get(url, function(data){
course_details= data;
});
split_course_details = course_details.split(',');
course_name=split_course_details[0];
course_price=split_course_details[1];
course_date=$("#date_range").val();
item_name=course_name+' - '+course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
</script>
Place your calculation inside the callback function of $.get(), like this:-
$(document).ready(function() {
url = "date_range.php?courseID=" + $('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID=" + $('#course_name').val();
var course_details;
$.get(url, function(data) {
course_details = data;
split_course_details = course_details.split(',');
course_name = split_course_details[0];
course_price = split_course_details[1];
course_date = $("#date_range").val();
item_name = course_name + ' - ' + course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
});
$('#course_name').change(function() {
url = "date_range.php?courseID=" + $('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID=" + $('#course_name').val();
var course_details;
$.get(url, function(data) {
course_details = data;
split_course_details = course_details.split(',');
course_name = split_course_details[0];
course_price = split_course_details[1];
course_date = $("#date_range").val();
item_name = course_name + ' - ' + course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
});
Try this:
$(function() {
var cname = $('#course_name'),
dates = $('#dates'),
iname = $('#item_name'),
amount = $('#amount'),
drange = $('#date_range');
cname.change(function() {
dates.load( 'date_range.php?courseID=' + this.value );
$.get('course_name.php?courseID=' + this.value, function(data) {
data = data.split(',');
iname.val( data[0] + ' - ' + drange.val() );
amount.val( data[1] );
});
}).change();
});
it seems like you're using url variable twice for different data...
try using additional variable..

Categories