I have this JQuery function used in a Thymeleaf template to submit the template to a specific URL, based on the value selected in a dropbox object, but it seems not to work
$('#selectAuthorizedDriverId').change(
function() {
var link = /*[[#{/deviceDriver/updateauthorizeddriver}/$('#selectAuthorizedDriverId').val();]]*/ "";
$('#deviceFormId').attr('action', link);
$('#deviceFormId').submit();
});
Do not use thymeleaf
var link = "/deviceDriver/updateauthorizeddriver/" + $(this).val();
Related
I am doing:
var url = '#Url.Action("Attachments", "Transactions")';
url += '/?id=' + 3201;
$("#attachments").load(url);
However, on load it doesn't do anything. Am i missing something?
I essentially want to call something similar to:
#{Html.RenderAction("Attachments", "Transactions", new { id = 3301 });}
I get the following error on console:
http://server:54137/Transactions/#Url.Action(%22Attachments%22,
You must be using an external JavaScript file which will not parse your razor syntax hence the error in your console of #Url.Action(%22Attachments%22..
You have a couple of options:
Create a JavaScript function and pass in the url:
function loadUrl(url) {
$("#attachments").load(url);
}
Then in your razor call it within a script tag:
loadUrl(#Url.Action("Attachments", "Transactions", new { id = #Model.Id })
Add the url to the html element as data and read it from your JavaScript with the data method.
In your razor markup add this:
<button data-url="#Url.Action("Attachments", "Transactions", new { id = #Model.Id })" />
From your JavaScript event handler read it with:
var url = $(this).data('url');
$("#attachments").load(url);
I prefer the second option.
You Need to use Html.Raw check below
var url = "#Html.Raw(Url.Action("Attachments", "Transactions"))";
url += '/?id=' + 3201;
$("#attachments").load(url);
I have MVC controller that returns a list containing a search string.
public ActionResult GetList(string searchString)
{
ViewData["searchString"] = searchString;
if (String.IsNullOrEmpty(searchString))
{
var persons = db.Persons.ToList();
return View(persons);
}
else{
var persons = db.Persons.Where(p=> p.Title.Contains(searchString)).ToList();
return View(persons);
}
}
In the view the list is displayed in a table. I want to highlight the searchString (or at most the td that contains the searchString). The following is my jquery where I attempted to achieve this. I have tried putting this bit of code in a separate .js script or in the view itself and I have also tried to change the code in several ways but it wouldn't work. It appears like the searchString remains null even if the content of my ViewData has changed.
$(document).ready(function () {
var textToHighligt = #ViewData["searchString"];
$("#simpleSearchButton").click(function () {
$("td:contains(textToHighligt)").css("background-color", "yellow");
});
});
I think this:
var textToHighligt = #ViewData["searchString"];
$("td:contains(textToHighligt)").css("background-color", "yellow");
should be concatenated:
var textToHighligt = '#ViewData["searchString"]'; //<---put in quotes
$("td:contains("+textToHighligt+")").css("background-color", "yellow");
I think you can do otherwise if it is not happening in the javascript file , create a hidden field and populate the value from the ViewBag
#Html.Hidden("hiddensearchString", (string)ViewBag.searchString)
For the ViewData
#Html.Hidden("FirstName", ViewData["searchString"])
and then the javascript read the value like this
var searchString = $("#hiddensearchString").val();
In you code you can also try this using of the single quote.
var textToHighligt = '#ViewData["searchString"]';
I would really appreciate some guidance. This is probably simple to some of you, but i can't figure it out.
Thanks for any input.
THE REQUIREMENT
I have a multi-tabbed control. One each tab, I have a custom reportviewer control.
I have added a custom attribute to the reportviewer in the code behind called "data-report-param".
I need to access the value of custom attribute "data-report-param" on the current tab on the client-side using javascript.
I have tried several ways including the following, but can't get to the value that is being created in the DOM.
MY CODE
//Attempt 1
var reportparamattribute = $('#ReportViewer1');
var reportparametervalue = reportparamattribute.getAttribute('data-report-param');
//Attempt 2
var reportparamattribute = document.getElementById('<%= ReportViewer1.ClientID %>');
var reportparametervalue = reportparamattribute.getAttribute('data-report-param');
//Also tried accessing the dataset
var reportparametervalue = reportparamattribute.dataset.report-param;
WHAT IS BEING PRODUCED IN THE DOM
('ctl00_m_g_66e41117_8ff5_4650_bf4d_7a4a25e326f3_ctl01_ReportViewer1_ctl04').control.HideActiveDropDown();" data-report-param="1068" interactivedeviceinfos="(Collection)">
('ctl00_m_g_9d6a6c3c_11d0_4e03_bbd2_b907172c437d_ctl01_ReportViewer1_ctl04').control.HideActiveDropDown();" data-report-param="1068" interactivedeviceinfos="(Collection)">
UPDATE- WORKING CODE BELOW
The key was passing the custom data attribute from the code behind and then accessing it in the $.cache as #popnoodles below indicated, and passing the clientID of the reportviewer into the javascript function to get to the current instance of the webpart child controls.
<input type="hidden" id="<%= ASP_SSRS.ClientID %>_myDataState"
onchange="compareUnitValues(this.id, this.parentNode.id, '<%= ReportViewer1.ClientID %>', '<%= ASP_SSRS.ClientID %>', '<%= btnSendHiddenField.ClientID %>');" />
<script type ="text/javascript">
function compareUnitValues(elemt, parent, reportviewerID, value1, value2) {
var myDataUnit = $("#" + elemt),
parentObject = $("#" + parent),
reportviewerObject = $("#" + reportviewerID),
ssrs = $("#" + value1),
btnSend = $("#" + value2);
var myDataUnitValue = myDataUnit.val();
var myDataUnitJSON = jQuery.parseJSON(myDataUnitValue);
var currentmyDataUnit = myDataUnitJSON.currentUnit.objectId;
var sessioncurrentObjectId = document.getElementById('<%= hiddenCurrentObjectId.ClientID %>').value;
ssrs.val(myDataUnitValue);
var currentReportViewerParam = $("#" + reportviewerID).attr("data-report-param");
if (currentmyDataUnit != currentReportViewerParam) {
btnSend.trigger("click");
}
}
FROM CODE BEHIND CREATE THE CUSTOM DATA ATTRIBUTE
ReportViewer1.Attributes.Add("data-report-param", parsedObjectId)
getAttribute will only give you the value that was in the generated or modified HTML not what is in the DOM. The data method never updates the HTML.
jQuery creates an empty object $.cache, which is used to store the values you set via the data method. Each DOM element you add data to is assigned a unique ID which is used as a key in the $.cache object.
Setting
$('#ReportViewer1').data('report-param', 1234);
Getting
var id = $('#ReportViewer1').data('report-param');
If you can use jquery why not just:
$("#reportviewer1").data('report-param');
I have a page called search.jsp. When the user selects a record and the presses an edit button, I would like to open a new page (in the same window) with the record data (that is stored in a json object and passed to the new page). How do I use Javascript (or jQuery) to open a new page and pass the JSON data?
If the two pages are on the same domain, a third way is to use HTML5 localStorage: http://diveintohtml5.info/storage.html
In fact localStorage is precisely intended for what you want. Dealing with GET params or window/document JS references is not very portable (even if, I know, all browsers do not support localStorage).
Here's some very simple pure JavaScript (no HTML, no jQuery) that converts an object to JSON and submits it to another page:
/*
submit JSON as 'post' to a new page
Parameters:
path (URL) path to the new page
data (obj) object to be converted to JSON and passed
postName (str) name of the POST parameter to send the JSON
*/
function submitJSON( path, data, postName ) {
// convert data to JSON
var dataJSON = JSON.stringify(data);
// create the form
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', path);
// create hidden input containing JSON and add to form
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", postName);
hiddenField.setAttribute("value", dataJSON);
form.appendChild(hiddenField);
// add form to body and submit
document.body.appendChild(form);
form.submit();
}
Use some PHP like this on the target page to get the JSON:
$postVarsJSON = $_POST['myPostName'];
$postVars = json_decode( $postVarsJSON );
Or, more simply for JavaScript:
var postVars = JSON.parse( <?php $_POST['myPostName']; ?> );
Assuming the two pages are on the same domain, you can use the returned object created by window.open() to access (and edit) the window object of a newly opened window.
Hmm, for example, you have object
var dataObject = {
param : 'param',
param2 : 'param2'
};
You can translate it into string, using JSON.stringify method
var dataObjectString = JSON.stringify(dataObject);
Then you should use Base64 encoding to encode you data (base64 encode/decode methods can be easely found in search engines)
var dataObjectBase64 = base64encode(dataObjectString);
You will get something like this
e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307
Then you can pass this string as a parameter:
iframe src="http://page.com/?data=e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307"
Finally, reverse actions on the loaded page.
You can create "on the fly" a form with a hidden/text input value this will hold the json value, then you can submit this form via javascript.
Something like this...
Im using JQUERY AND UNDERSCORE(for template purpose)
this is the template
<form method='<%= method %>' action="<%= action %>" name="<%= name %>" id="<%= id %>" target="_blank">
<input type='hidden' name='json' id='<%= valueId %>' />
</form>
you can then post use it on javascript
function makePost(){
var _t = _.template("use the template here");
var o = {
method : "POST",
action :"someurl.php",
name : "_virtual_form",
id : "_virtual_form_id",
valueId : "_virtual_value"
}
var form = _t(o); //cast the object on the template
//you can append the form into a element or do it in memory
$(".warp").append(form);
//stringify you json
$("#_virtual_value").val(JSON.stringify(json));
$("#_virtual_form_id").submit();
$("#_virtual_form_id").remove();
}
now you dont have to be worry about the lenght of you json or how many variables to send.
best!
If the the JSON is small enough you can just include it as a GET parameter to the URL when you open the new window.
Something like:
window.open(yourUrl + '?json=' + serializedJson)
Assume if your json data
var data={"name":"abc"};
The page which sends JSON data should have the following code in the script tag.
$.getJSON( "myData.json", function( obj ) {
console.log(obj);
for(var j=0;j
<obj.length;j++){
tData[j]=obj;
//Passing JSON data in URL
tData[j]=JSON.stringify(tData[j]);
strTData[j]=encodeURIComponent(tData[j]);
//End of Passing JSON data in URL
tr = $('\
<tr/>
');
//Send the json data as url parameter
tr.append("
<td>" + "
" +Click here+ "" + "
</td>
");
}
});
The page which receives the JSON data should have the code.
<html>
<head></head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<body>
<p id="id"></p>
</body>
<script type="text/javascript">
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.jsonDATA);
var name=data.name;
console.log(name);
document.getElementById("id").innerHTML=name;
} catch (err) {
alert(err + "\nJSON=" + q.team);
}
</script>
</html>
I'm trying to submit a form using Jquery's ajax. It has got a few textboxes, some checkboxes, and a multiple options' dropdown (i.e multiple options can be selected).
Someone here told me that I can get values of all selected checkboxes using
$("input:checkbox[name=type]:checked")
Then I can loop through all the values returned by the above code, assign them to an array like this:
var types=new Array();
$.each(cboxes, function()
{
types[types.length]=$(this).val();
}
);
And try to submit the form using this:
var someField=$("#someField").val();
var someField2=$("#someField2").val();
var data={field1 : someField, field2=someField2, s_types:types};
$.post("signup.php?type=p",types);
But that doesn't work, specifically the checkboxes don't get submitted correctly. How can I make it work?
It's not necessary to iterate over each field to get the form values. jQuery has a method to serialize form inputs into a querystring. You can do this:
$.ajax({
url: "mybackend.php",
data: $("#myForm").serialize(),
success: function(e) { // do something on success },
error: function(e) { // do something on error }
});
Remember that javascript posts always send data in UTF-8 format, so be sure you're expecting that on the backend if you plan to send text with international characters.
I recommend using a plug-in to do that. Have a look at this form plug-in. It also can integrate nicely with validation plug-in.
The default jQuery $.param doesn't handle arrays (by design), so you can't use $.serialize as it is. Use either a plugin, like suggested in kgiannakis' answer, or overwrite the $.param function so it'll handle arrays properly:
function($) {
$.param = function(a) {
var s = [];
if (a.constructor == Array || a.jquery)
jQuery.each(a, function() { s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) ); });
else
for (var j in a)
if (a[j] && a[j].constructor == Array) jQuery.each( a[j], function(){ s.push( encodeURIComponent(j) + "[]=" + encodeURIComponent( this ) ); });
else s.push(encodeURIComponent(j) + "=" + encodeURIComponent(a[j]));
return s.join("&").replace(/%20/g, "+");
};
})(jQuery);
...and then use $.serialize, like suggested by Danita.