I am trying to replace the content that pastes in the Textarea, but facing a problem that it shows in the Textarea the original content and the "modified" content both. Hope you can help me.
HTML Code (just a simple textarea):
<textarea name="Notes_999" class="cssDetail" id="Notes_999" autocomplete="off"> </textarea>
The Jquery code:
$(".cssDetail").bind("paste", function(e){
// access the clipboard using the api
var elemID = $(this).attr("id");
console.log("elemID: " + elemID);
var t_string = "";
var pastedData = e.originalEvent.clipboardData.getData('text');
console.log("pastedData " + pastedData );
var arrayOfLines = pastedData.split('\n');
$.each(arrayOfLines, function(index, item) {
var cnt_spaces = item.search(/\S|$/);
console.log("cnt_spaces: " + cnt_spaces + " - line: " + item);
item = item.replace(/^\s+|\s+$/g, '');
if (cnt_spaces == 8) {
t_string += "- " + item + '\n';
} else {
t_string += item + '\n';
}
});
//console.log("elemID: " + elemID);
$("#"+elemID).text(''); // Try to clean before replace new content but not working.
$("#"+elemID).text(t_string);
});
The function above works fine and does what I expected. However, the result inside the Textarea has both the original and the "modified " one (t_string variable). I only want the "modified" one in the textarea, please help.
Thank you,
I'm trying implement a like button that changes color when clicked. I am trying to replace the image dynamically using jQuery.
<div class = "col-sm-10" style = "margin-top: 2%">
<input style = "width : 4%; height: 4%" type = "image" id = {{schedule.id}} + "image" class = "likes"
data-scheduleid = "{{schedule.id}}" data-user = "{{curruser.person.id}}"
src = "{% static 'img/notliked2.png' %}"/>
</div>
This is image file that gets pressed as a button. Essentially, I am trying to change the image file on click.
$(document).ready(function() {
$('.likes').click(function(e){
var sched_id;
var curruser;
sched_id = $(this).attr("data-scheduleid");
curruser_id = $(this).attr("data-user");
$.get('/profiles/like_schedule/', {schedule_id: sched_id, current_user: curruser_id}, function(data){
var first = data.split("/")
$('#' + sched_id).html(first[0]);
console.log(first[1])
//$('#likes').html("<input style = 'width : 4%; height: 4%' type = 'image' id = {{schedule.id}} class = 'likes' data-scheduleid = '{{schedule.id}}' data-user = '{{curruser.person.id}}' src = {% static 'img/" + first[1] + "' %}/>");
$('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}")
e.preventDefault();
});
});
});
This is the jQuery. I logged first[1], and it is correct. It alternates between "notliked2.png" and "liked2.png" when someone likes and unlikes. But for some reason replacing the image source doesn't work. I even tried replacing the entire html, and it still doesn't work. Does someone know what is going on?
Thank you,
Albert Jin
edit:
Here is the views code.
def like_schedule(request):
sched_id = None
if request.method == 'GET':
sched_id = request.GET['schedule_id']
curruser_id = request.GET['current_user']
likes = 0
liked = "liked2.png"
if sched_id:
sched = schedules.objects.get(id = int(sched_id))
curruser = person.objects.get(id = int(curruser_id))
if curruser in sched.person_likes.all():
liked = "notliked2.png"
sched.likes -= 1
sched.person_likes.remove(curruser)
else:
sched.likes += 1
sched.person_likes.add(curruser)
likes = sched.likes
sched.save()
return HttpResponse(str(likes) + "/" + str(liked))
As for the repeat posts, I did try those but they do not work.
You are using django sytax in your javascript code. You cant use the static function like this:
$('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}")
I would replace the current url and only replace the dynamic part of the url, like so:
var src = $('.' + sched_id + "image").attr("src");
$('.' + sched_id + "image").attr("src", src.slice(0, src.indexOf('img/')) + 'img/" + first[1]);
Not sure of how is the format of the $.get response (you don't show it in the question), but looking at your code this should be enough...
$(document).ready(function() {
$('.likes').click(function(e) {
e.preventDefault();
var $img = $(this);
$.get('/profiles/like_schedule/',{ schedule_id: $img.data("scheduleid"), current_user: $img.data("user") }, function(data) {
$img.attr('src','img/' + data.split("/")[1])
});
});
});
One posible problem is that you're having a caching problem, so your get call is not being executed. If that's your case, you can force your server to execute that call just adding some extra inconstant parameter...
$.get('/profiles/like_schedule/',{ dummy: (new Date()).getTime(), schedule_id: $img.data("scheduleid"), current_user: $img.data("user") }, function(data) {
$img.attr('src','img/' + data.split("/")[1])
});
NOTE: When you want to get the value of a data-whatever attribute in jquery, you have the .data('whatever') function (is designed for that).
So I have this code that I am trying to alter –
Original:
jQuery(document).ready(function() {
var name = '';
var firstLastName = '[[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.first_name]]]] [[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.last_name]]]]';
var screenname = '[[T6:[[S48:0:screenname]]]]';
if (screenname) {
name = screenname;
} else {
name = firstLastName;
}
var splitName = name.split('');
var nameCheck = splitName[splitName.length-1];
jQuery('#personal_page_header h2').html("Support " + name + "'s Fundraiser" );
});
someone wrote this up and are no longer here, and what I'm trying to do now is figure out how to instead of replace the existing text, add to it.
So right now what this code does is it replaces the h2 content with the constituents registered name, or screenname.
What I'm trying to do now is append to that so that it will say something like
<h2>
Welcome to my fundraiser
<br/>
"Support" + name + "'s Fundraiser"
</h2>
but unfortunately what I tried breaks the code and stops it from working.
what I tried to do is this:
jQuery('#personal_page_header h2').append('<span><br />"Support " + name + "'s Fundraiser"</span>' );
I've tried to do a variety of other things that gave the same unsuccessful result.
Any help would be really appreciated!
Thanks
This should work for you:
jQuery('#personal_page_header h2').append("<span><br/>Support " + name + "'s Fundraiser</span>");
You've just got your quotations a little out of place.
You need to concatenate your code correctly, so if you'd like to keep the " use ' to concatenate. Further you need to escape the ' inside the string with \:
jQuery('#personal_page_header h2')
.append('<span><br />"Support ' + name + '\'s Fundraiser"</span>');
I am new to JQuery.
Trying to create a blog page. When user enters name, country and comment, i want to print it out underneath the HTML form.
The script i'm using is as follows:
<script>
$(document).ready(function() {
$(".addButton").click(function() {
var name = $("input[name=name]").val();
var country = $("select[name=countries]").val();
var comment = $("textarea[name=comment]").val();
$(".comments").append("<div class='new-comment'>" + name + " (" + country + "):</br>" + comment + "</div>");
});
});
This prints out my variables but only for a fracture of a second and they disappear. Any explanation would be highly appreciated.
Thank you.
<button> tags will submit the form, causing the page to reload. Use Event.preventDefault() to stop the form submission.
$(document).ready(function() {
$(".addButton").click(function(e) {
e.preventDefault();
var name = $("input[name=name]").val();
var country = $("select[name=countries]").val();
var comment = $("textarea[name=comment]").val();
$(".comments").append("<div class='new-comment'>" + name + " (" + country + "):</br>" + comment + "</div>");
});
});
I have seen some posts regarding this topic and a few blogs, but none seem to mention the output I'm getting.
What I want is to generate a google maps map with information on it. Manually entering the information results in the correct information. So that part works.
Where I'm getting stuck is when I'm going to dynamiccaly create the javascript array with the string with the information I want on my map.
The html code I want to get is:
<script type="text/javascript">
var projects = [
['Kantoor 4.1 bestaande bouw', 52.25446, 6.16024700000003, 'Deventer', '', 'adviseurs', 'rating30'],
['School nieuw 4.0', 52.243161, 4.43677860000003, 'Noordwijk', '', 'adviseurs', 'rating30'],
];
Very simple javascript array, which I thought to create with:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
#HttpUtility.JavaScriptStringEncode("['" + item.Gebouwnaam + "', " + item.LocatieLatitude.ToString().Replace(",", ".") + ", " + item.LocatieLongitude.ToString().Replace(",", ".") + ", '" + item.Plaats + "', '" + item.Gebruiksfunctie + "', '" + item.Licentiehouder + "', '" + item.rating + "'],");
}
];
</script>
However this gives me:
<script type="text/javascript">
var projects = [
[\u0027Kantoor 4.1 bestaande bouw\u0027, 52.25446, 6.16024700000003, \u0027Deventer\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
[\u0027School nieuw 4.0\u0027, 52.243161, 4.43677860000003, \u0027Noordwijk\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
];
</script>
Escaping the single quotes doesn't work.
What am I doing wrong?
Just tried with
<script type="text/javascript">
var projects = [
#Html.Raw("['" + "aaa" + "', '" + "bbb" + "'],")
];
</script>
it worked and showed ...
<script type="text/javascript">
var projects = [
['aaa', 'bbb'],
];
</script>
You don't want to call JavaScriptStringEncode on the entire string, that will also encode your literal indicators (which are being converted to \u0027 in your example). Instead, call it on each item in your array like this:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
String.Format("['{0}',{1},{2},'{3}','{4}','{5}','{6}']",
HttpUtility.JavaScriptStringEncode(item.Gebouwnaam),
HttpUtility.JavaScriptStringEncode(item.LocatieLatitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.LocatieLongitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.Plaats),
HttpUtility.JavaScriptStringEncode(item.Gebruiksfunctie),
HttpUtility.JavaScriptStringEncode(item.Licentiehouder),
HttpUtility.JavaScriptStringEncode(item.rating)
)
}
];
</script>
I believe you could do most of the heavy lifting in .net and leverage Html.Raw to transform the object for you:
#{
var myObj = Model.Select(i => new {
item.Gebouwnaam,
item.LocatieLatitude.ToString().Replace(",", "."),
item.LocatieLongitude.ToString().Replace(",", "."),
item.Plaats,
item.Gebruiksfunctie,
item.Licentiehouder,
item.rating }).ToArray();
}
<script type="text/javascript">
var jsObj = #Html.Raw(Json.Encode(myObj));
</script>
Since it's touched on in this question, HttpUtility.JavaScriptStringEncode() comes in really handy for strings containing newline characters:
#{ var myNetString = "Hi,\r\nMy name is Joe\r\nAnd I work in a button factory"; }
<script type='text/javascript'>
var myJsString = '#HttpUtility.JavaScriptStringEncode(myNetString)';
</script>