I have written this small piece of razor code with java script:
#Html.ActionLink("ערוך", "Edit", new { id = item.tz }) |
#Html.ActionLink("הצג פרטים מלאים", "Details", new { tz = item.tz }) |
#{
var shem = ("האם אתה בטוח שברצונך למחוק את" + #Html.ValueFor(model => item.fname) + " " + #Html.ValueFor(model => item.lname) + "?");
#Html.ActionLink("מחק", "Delete", new { id = item.tz }, htmlAttributes: new { onclick = "return confirm('shem');"} )
}
All I want is for the variable to be displayed in the "return confirm," but for some reason it doesn't recognize that as a variable and will only write it down literally.
Things I've tried so far:
Putting the while variable in the "return confirm" and avoid using a variable completely.
Putting the name of the variable with an # in front of it.
removing the whole thing from the #{} (which caused the whole variable line to be rendered as a in the HTML page).
Removing the '' around the variable's name in the "return confirm."
So what am I doing wrong? I'm sure it'll end up being a small syntax thing, but I just can't figure it out...
Try like this:
onclick = "return confirm(" + Json.Encode(shem) + ");"
Related
This is in reference to dynamically change options in a list by another list. Unfortunately, it all works except if the project name has a " or a #. Eg. Project name: '10" Centerline #3 Pipe'
I am a newbie to this and I have been cut/paste (learning) as I go along. If someone can help, it will be great. I am seen some things about escaping and encoding URI stuff but not sure where to put it in. The other problem is just understanding what happens past the onchange event.
I can get the list of project names from a previous list and it shows up in my HTML page. However, when I select the choices that have a ( " ) or a ( # ), the next populated list breaks.
Thanks in advance. I really, really appreciate the time if someone puts in a response.
Here is the javascript portion:
project_name_select.onchange = function(){
project_name = project_name_select.value;
fetch('/sr/new/project/' + project_name).then(function(response){
response.json().then(function(data) {
var areaHTML = '<option value="See List">Select Area</option>';
for (var state of data.project_area) {
areaHTML += '<option value="' + state.project_area + '">' + state.project_area + '</option>'
}
project_area_select.innerHTML = areaHTML;
});
});
}
Here is the flask portion:
#surveys.route("/sr/new/project/<get_project_name>")
def project(get_project_name):
project_dict, dict_type = choice_project_dict(get_project_name)
project_areaArray = []
for proj in project_dict:
ownerObj = {}
ownerObj['id'] = proj['company_name']
ownerObj['owner_company'] = proj['company_name']
ownerArray.append(ownerObj)
return jsonify({'project_area': project_areaArray})
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 developing MVC application and using razor syntax.
I want to use HTML code in JavaScript in cshtml file, but I get confused about how to use double quotes in JavaScript in razor syntax. Is that matter?
This is line of code:
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" id = "#item.Id" class="deleteComment">Delete</button></span>
And I have written below code in JavaScript, is that right?
success: function (data) {
$("p.p12").append
("<div style=\"background-color:#FAFAFA\";>Recently Added... <br />" + data.OwnerName + ""
+ data.cmtDateTime + "<button type=\"button\" id = \" + data.Id + "\class=\"deleteComment\">Delete</button></span><br />" + data.msg + "</div>");
}
and I have written below code in JScript is that right ?
No, it doesn't seem right. The generated HTML is broken. You need to be more careful about the syntax, things liks spaces between the attributes and the quotes are important. Also you seem to be hardcoding urls instead of using url helpers. Try like this:
$('p.p12').append(
'<div style="background-color:#FAFAFA;">Recently Added... <br />' + data.OwnerName + '' + data.cmtDateTime + '<span><button type="button" id=' + data.Id + ' class="deleteComment">Delete</button></span><br />' + data.msg + '</div>'
);
or as I suggested you here which IMHO is more correct approach.
or since you are using an AJAX call, instead of returning JSON from your controller action, return a ParialView in which you will correctly build the markup using proper HTML helpers.
Like this:
[HttpPost]
public ActionResult SomeAction(SomeViewModel args)
{
MyViewModel model = ...
return PartislView("_SomePartial", model);
}
and then inside your strongly typed partial (_SomePartial.cshtml) build the markup without any string concatenations and spaghetti code mixing javascript and HTML:
#model MyViewModel
<div style="background-color:#FAFAFA;">
Recently Added...
<br />
#Html.ActionLink(Model.OwnerName, "Details", "Employee", new { id = Model.OwnerID }, null)
#HtmlDisplayFor(x => x.cmtDateTime)
<span>
<button type="button" id="#Model.Id" class="deleteComment">Delete</button>
</span>
<br />
#HtmlDisplayFor(x => x.msg)
</div>
Now all that's left in your AJAX success callback is to refresh the corresponding DOM section:
success: function(html) {
$('p.p12').append(html);
}
I'm trying to generate a series of check boxes that will update a span to keep track of the number of check boxes that have been checked (shows something like "4 of 12 checked"). I've created the JavaScript function updateSelected that handles that, but it requires the ID of the span and the class of the check boxes to count, so I tried this code to generate each check box:
#Html.CheckBox(string.Format("contentprofilestate[{0}].selected", i),
new { onclick = "updateSelected('" + selectedSpanId + "', '" + checkboxClass + "')" })
This produces the following HTML:
<input id="contentprofilestate_6__selected" name="contentprofilestate[6].selected"
onclick="updateSelected('StMarySpan', 'StMaryCheck')"
type="checkbox" value="true" />
How can I get the onclick event handler to render without escaping the apostrophes? Alternatively, is there a better way to accomplish this task (if so, feel free to use jQuery in your suggestion)?
Note re: Lester
I created a new project and created this view and it still escaped the apostrophes:
#{
ViewBag.Title = "index";
}
<h2>index</h2>
#Html.CheckBox(string.Format("contentprofilestate[{0}].selected", 0), new { onclick = "updateSelected('" + "test" + "', '" + "test2" + "')" })
Alternate Solution
I was not able to figure out how to keep the apostrophes from being escaped, so I wrote some jQuery logic to do what I need without any inline JavaScript:
jQuery(document).ready(function () {
jQuery(':checkbox').click(function () {
var clientHeader = jQuery(this).closest('.client-header');
var clientCheckedSpan = clientHeader.find('.client-checked');
var inputChecked = clientHeader.find('input:checked');
clientCheckedSpan.text(inputChecked.length);
});
});
It's very odd that the apostrophes are being encoded. I didn't think they would be and after doing a quick test they aren't. There's probably something else going on in that view. If you place just that 1 line in an empty view I'm betting you won't get the same problem.
As for any other alternatives, you can easily get the number of selected checkboxes using jQuery:
var numChecked = $("input:checked[id^=contentprofilestate]").size();
I finally got my back-end to create the wheel codes from the checked taxonomies in the add custom post admin area.
Now, I want to add that tire code to the wheel_type taxonomy.
The below code ran great, until I added the if statement under //Add code to Taxonomy
Now nothing is working, but I get nothing in the error console.
I figure it must be a stupid syntax mistake - can anyone help me out?
Or am I missing something else?
jQuery('#replace').click(function(){
//get tire code and name
var code = jQuery('input[name="tire_code"]').val();
var name = jQuery('input[name="tire_name"]').val();
var bname = jQuery('input[name="tire_bname"]').val();
alert(code + " + " + name + " + " + bname);
//get tire brand
var tirebran = jQuery('#tire_brandchecklist').find(":checked").parent('label').text();
tirebran = jQuery.trim( tirebran );
//Add code to Taxonomy
if( term_exists( code, wheel_type ){
continue;
}
else
{
wp_insert_term( code, wheel_type );
}
//update title
var title = code + ' : ' + name + ' tires';
if(tirebran!=''){
title += ' with ' + bname + ' letters';
}
jQuery('input[name="post_title"]').focus().val(title);
});
//-->
</script>
unless i've misunderstood your question, you're trying to call wordpress methods via javascript.
term_exists() and wp_insert_term() are PHP methods within the wordpress code, not accessible directly via Javascript (unless you have written interfaces to them).
continue doesn't make any sense there; just check for !term_exists... and call wp_insert_term when it doesn't exist.
if (!term_exists(code, wheel_type)) {
wp_insert_term(code, wheel_type);
}
The continue statement is for continuing loops from the top of the loop; it does not stand on its own.