I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)
<a class="" href="/LaborerSearchByName/Index">
<img src="/Content/images/b7.png" id="b7"
onclick="bb7();"
onmouseover="bigImg(this)"
onmouseout="normalImg(this)">
</a>
The call for action link
#Html.Action("Menu", "MenuItem", new { id = "MenuId"})
"MenuId" must by a dynamic value based on which button is clicked.
Here goes my solution, use Html.ActionLink() -
#Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { #id = "MenuId" })
Then say you have image control like this -
<img src="/Content/images/b7.png" id="b7"/>
Then you have simple JQuery script to replace query string in this way -
<script>
$(document).ready(function () {
$("#b7").click(function () {
$("#MenuId").attr("href","/MenuItem/Menu/" + this.id);
});
});
</script>
In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7
UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
public JsonResult GetJson(string MenuId)
{
List<string> urls = new List<string>();
urls.Add("https://google.com");
urls.Add("https://bing.com");
return Json(urls, JsonRequestBehavior.AllowGet);
}
Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.MenuId = $("#Menu").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {ou parse data
// This is how we parse returned json string
$.each(data, function (i, item) {
alert(data[i]);
});
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
When you run the code, you should see following view -
When you enter the value and click on anchor tag -
And as a result, you will get all the results parsed -
You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}
Related
I have a button when that button is clicked I want to set a model property to true and be able to receive it in the back end. Code is a bit messed up but bear with me please as I have taken alot of code out of it.
#model FullConfigurationMV
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(model => model.IsTemplate)
// Code removed for brevity
<button id="DraftName">Click me</button>
}
<script>
$( document ).ready(function() {
debugger;
$("#DraftName").click(function()
{
#Model.IsTemplate = true; // I AM SETTING THE VALUE AS TRUE
SaveStyles();
});
});
</script>
<script>
function SaveStyles() {
var data = $('#MyForm').serialize();
var URL = "SOME URL"
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
},
error: function (error) {
}
});
}
</script>
POST ACTION
public JsonResult SaveStyles(FullConfigurationMV data)
{
// data.IsTemplate is coming out to be false
// Rest of the UI control data is coming back properly
}
EDIT
Since I have below code. is that the issue?
var data = $('#MyForm').serialize();
Think about this problem a little differently.
All the view does is render html. Since you have a form in html, all your javascript has to do is to set the form element's value to true.
You should be able to use the jQuery selector like
$('input:hidden[name=IsTemplate]').val(true);
And your form serialize should pick it up.
Razor view are generated in server side. So when you browser get the HTML there is no razor code in it so the following code will not work:
$("#DraftName").click(function()
{
#Model.IsTemplate = true; // <-- this will not work and will not exist in client side
SaveStyles();
});
You should set the hidden field you just put in your form #Html.HiddenFor(model => model.IsTemplate) which generate <input type='hidden' /> and just update your javascript code by doing this:
$("#DraftName").click(function()
{
$("#MyForm input[type='hidden']").val("true"); // <- Replace your Razor code with this.
SaveStyles();
});
I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.
I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?
Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')
Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}
I have a simple ajax request which get from server a generated HTML, like:
$.ajax({
url: '/GetData'
type: "POST",
dataType: "html",
data: ...,
success: function(data) {
// here I want to change `name` attributes of inputs
// before print on page
// but it doesn't work, so, how to manage this ?
$(data).find("input[name='test']").prop("name", "anotherValue");
$("myDiv").prepend($(data));
}
});
and my action is simple:
[HttpPost]
public ActionResult GetData(){
return PartialView("myview", new MyModel());
}
I want to change input name attributes before print them in html page. If I do in success function (see above) then no change is made.
Why ? To to achieve this ?
try something like
$("input").each(function() {
if($(this).prop("name") == "test") $(this).prop("name", "anotherValue");
});
Data cannot be edited unless you append them to the DOM
So, use String.Replace function
var removed=data.replace("name='test'","anotherValue")
.replace('name="test"',"anotherValue");
$("myDiv").prepend(removed);
or do this
$(data).prependTo("myDiv").find("input[name='test']").prop("name", "anotherValue");
What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data