HTML Table: Edit button trigger Javascript event - javascript

I have a HTML table which I am populating with PHP.
I have
<td><a class='Edit_Btn' data-value='".$row["Driver_Reference"]."' onclick='Edit_Btn_Click();' href='#'>Edit</a></td>
to build the edit button for each for.
I am trying to avoid using JQuery, but I need to write a Javascript function to get the data-value of the respective edit button that has been pressed, so I can perform the relevant action (in this case it will take me to another page).
Here is what I tried already:
function Edit_Btn_Click(Driver_Reference) {
var Driver_Reference = this.dataValue;
alert("Edit button pressed! Artist ID: " + Driver_Reference);
}

this in your existing function doesn't refers to your element. Change the the HTML and pass current element context to inline click handler i.e. onclick='Edit_Btn_Click(this);'
<td><a class='Edit_Btn' data-value='".$row["Driver_Reference"]."' onclick='Edit_Btn_Click(this);' href='#'>Edit</a></td>
Then modify your function as
function Edit_Btn_Click(elem) {
var Driver_Reference = elem.dataset.value;
alert("Edit button pressed! Artist ID: " + Driver_Reference);
}
In the above function, You can use Element.dataset property to access the data.

You can use:
this.getAttribute('data-value');

Related

Setting a onclick event to a c# URL Action in javascript?

In my view I have a checkbox input as follows:
<input type="checkbox" data-toggle="modal" data-target="#CheckItemsModal" id="#item.ItemId" onclick="location.href = '#Url.Action("CheckedItem", "List", new { id = item.ItemId })'; Checked(this.id)" />
I am trying to have a modal confirmation on the checking and un-checking of the checkbox however this means that my URL action would need to be moved to the modal's button while still preserving the id = item.ItemId so my plan is to us javascript to do this however I am not sure how to assign the onclick event of the modal button properly.
This is what I have so far (The error it's throwing is that checkId inside the url action does not exist in the current context):
function Checked(checkId) {
if ($(checkId).Checked == true) {
$(modalButton).setAttribute('onclick','location.href = '#Url.Action("CheckedItem", "List", new { id = checkId })'')
}
}
Any help would be much appreciated.
C# is run on the server and JavaScript in the browser. Your URL.Action is executed on the server where the checkId variable does not exist. You need to generate the url from pure JavaScript in the onclick method or generate links using Url.Action for all checkboxes in advance.
Another option is to use string replace in the JavaScript onclick method. For example:
location.href = '#Url.Action("CheckedItem", "List", new { id = "_REPLACE_ID_" })'.replace( "_REPLACE_ID_", checkId);
Look at the generated HTML source to see what happens.
You also need to be careful about your quotes. In your code you have invalid JavaScript with multiple consecutive single quotes at the end.

How can I pass an argument to a function when I have called it in the href tag

I am creating a apraisal web application , Please help me solve this logic/syntax issue : I want to create a table with the cell content as hyperlink , so that when the user clicks on the link it will open a new window to accept data , also it should display the content of the cell clicked on the next page.
Here is my Javascript code:
row = table.insertRow(-1);
var cell = row.insertCell(-1);
cell.innerHTML = '<a href="#" onclick = func(name);>'+name+'</a>';
function func(name)
{
localStorage.setItem("Selectedname",name);
window.location.href="form_apraise.html";
}
Thank you
try this one with enable pop
window.open('https://stackoverflow.com/', '_blank');
cell.innerHTML = '<a onclick="func("' + name + '");">' + name + '</a>';
This should work. You don't really need the href attribute as that's not very useful in this case. Any element responds to an onclick event.
You could also put the parameters in additional attributes:
cell.innerHTML = '<a data-name="' + name + '" onclick="func();">' + name + '</a>';
Then in your func() you use this.dataset.name
More on this here
Use 'this' as a reference to the cell on which click event is fired.
cell.innerHTML = ''+name+'';
Access the cell value using the element.text
function func(elem)
{
var name =elem.text;
localStorage.setItem("Selectedname",name);
window.location.href="form_apraise.html";
}
You have a lot of options here, but I will tell you 3 of them:
1- Normally you could just send the parameter in your URL and that will be handle by your backend, like this: http://www.example.com/viewName/myName an then you could use window.open(URL, '_blank') that will open a new window
2- You could use a Popup window that get the information with AJAX and show the popup window to accept whatever you want to do.
3- You could create your cell with data-name attribute, assign one class to your cell and with any library or by Javascript only assign an event to all the elements with that class, read the attribute and call window.open(URL, '_blank') something like this:
<tr><td class="myClass" data-name="Your Name">Your Name</td></tr>
In javascript(jQuery):
$(document).ready(function(){
$(".myClass").click(function(){
window.open("http://example.com/"+$(this).data("name"),"_blank")
})
})
In your case the easy way is just pass the name as parameter, open a new window and then show the client the information about that name.

Change script data-location for a <script> inside HTML

I would like to modify one tag using javascript. I have a textbox to introduce a postcode and a button to find car parks near the position. The HTML tag is the following:
<script src="http://en.parkopedia.co.uk/js/embeds/mapView.js" data-Location="http://en.parkopedia.co.uk/parking/ST84JF/" data-options="l=0&tc=0&zc=1&country=UK&ts[]=4&ts[]=3&ts[]=2" data-size="750:400" type="text/javascript"></script>
I have two questions:
Can I modify the data-location to add the text write inside the textbox to search in that location?
Can I activate the script only when the button is clicked using javascript or jquery? The main problem here is that the should be inside the HTML code and I don't know how to put it inside the javascript file.
Code updated:
function find(){
$("script[id=script_map]").remove()
var search = document.getElementById('box_txt').value ;
$("<script />", {
"src":"http://en.parkopedia.co.uk/js/embeds/mapView.js",
"data-location":"http://en.parkopedia.co.uk/parking/" + search,
"data-options":"l=0&tc=0&zc=1&country=UK&ts[]=4&ts[]=3&ts[]=2",
"data-size":"750:400",
"id":"script_map",
"type":"text/javascript"
}).appendTo("#divId")
}
Try modifying data-location of script element before appending script element to body at click event of button element . Could alternatively use $.getScript() to retrieve script from external source
$("button").click(function() {
var val = $("input").val();
// Can I activate the script only when the button is clicked
$("<script />", {
"src":"http://en.parkopedia.co.uk/js/embeds/mapView.js",
// Can I modify the data-location to add the text write inside the textbox
// to search in that location?
"data-location":"http://en.parkopedia.co.uk/parking/ST84JF/" + val,
"data-options":"l=0&tc=0&zc=1&country=UK&ts[]=4&ts[]=3&ts[]=2",
"data-size":"750:400",
"type":"text/javascript"
}).appendTo("body")
})
Yes the data-location is simply a custom attribute i believe so just use
document.getElementById("SCRIPTTAGID").setAttribute("data-location", "newValue");
As far as activating the script to execute when a button is pressed you will need to encapse it in a function then call the function in the onClick event of the button.

How to submit a form by clicking a link javascript

currently I'm trying to make it so that when the user clicks a link it submits the corresponding form via javascript. I used document.getElementById("id").submit() as a basis on how to send the form so my code should act similar to it in my understanding.
Here's the code:
function run(clickedLink){
clickedLink.id.submit(); //I did it like this since document.getElementById just gets the form id and since link and form have similar id's I thought it would send
}
<form id = 'formId'>
<a href = '#' id = 'formId' onclick = run(this)>Link</a>
</form>
I tried going with name = 'formId' too but it still doesn't run as I wanted it too.
Note: doing this since this code iterates dynamically and the id gets updated i.e. formID1, formID2...
Better ways to implement this are welcome too
Modify your function as follows
function run(clickedLink){
clickedLink.parentNode.submit(); // parentNode refers to the form element
}
You cannot use same id on the same page for more than one element. This is against HTML and DOM specifications https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really .
You can change it to class if you want to reuse or you can change the id itself of other element. Also links are not recommended to submit the form. Their job is to navigate
Try this:
<a href="#" onclick="document.forms[0].v.value='Link1';
document.forms[0].submit();">Link 1</a>
One Basic thing:
-ID's are used to Uniquely Describe The Element in DOM Hierarchy. Please Don't Repeat it. (it is really bad)
Now to the answer:
function run(x){
var y=findParentForm(x); /* if Id's aren't Unique */
// If iD's are Unique :- var y=document.getElementById("formId");
y.submit();
}
function findParentForm(elem){
/*
This function will find exact parent form
even if link or elem is inside <div> or other complex DOM structure
This will Only return the parent <form> of that elemnt
*/
var parent = elem.parentNode;
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}
<form id='formId' action="Server Side Script" method="GET/POST">
Link <!-- change id of link -->
</form>

Is it possible to get the HTML of a jQuery created element before it has been inserted into the DOM Tree?

Here's what I've got:
gridComplete: function() {
var doneButton = $('<input>', {
type: 'button',
value: 'Done',
click: function() {
alert("Done!");
}
});
console.log("HTML:", doneButton.html());
var ids = $(this).jqGrid('getDataIDs');
var self = this;
_.each(ids, function(id) {
$(self).jqGrid('setRowData', id, {
MarkDone: doneButton.html()
});
});
}
If I just try and insert the doneButton object, the jqGrid cell renders [object Object] instead of the actual button. As such, I can infer that it is expecting raw HTML. However, doneButton.html() returns an empty string... presumably because I have not appended the doneButton object onto the document yet.
Is there a trick to doing this with jQuery? I'd prefer the cleaner/safer syntax for generating the HTML markup, but I can do this:
gridComplete: function() {
var doneButtonHtml = "<input type='button' value='Done' onclick=\"alert('Done');\" />";
var ids = $(this).jqGrid('getDataIDs');
var self = this;
_.each(ids, function(id) {
$(self).jqGrid('setRowData', id, {
MarkDone: doneButtonHtml
});
});
},
which renders the button as expected.
You get an empty string from your button because html() returns the inner HTML.
You probably want doneButton.get(0).outerHTML
If I correct understand what you want you can do the same using another way. To reduce the number of web browser reflows jqGrid build grid body disconnected and then inserts it at one. One have to use gridview: true to have the performance advantage. The problem is only that jqGrid build grid body as HTML string and not as DOM. jqGrid provide custom formatters, cellattr and rowattr callbacks which allows to construct custom column content or set some custom attributes on rows. See the answer for details.
So what you should do is
provide custom formatter for column MarkDone with the content "<input type='button' value='Done' />" (without click) event handler
use onCellSelect or beforeSelectRow callback to catch click event in any place of grid body inclusive the click on "Done" button. The event bubbling (see here) helps to reduce the number of event handles needed in the grid. $td = $(e.target).closest("td") will get you the cell which was clicked, iCol = $.jgrid.getCellIndex($td[0]) will get you the column number and this.p.colModel[iCol].name will get you the name of the clicked column.
The answer, another one and the oldest one will get you code examples and additional information which you need.
Change this:
MarkDone: doneButtonHtml.html()
To:
MarkDone: doneButtonHtml.get(0)
doneButtonHtml is a DOM elements array. You need to call get(0) to get the first element in that array.
The first thing to keep in mind is that .HTML() actually retrieves the html inside of an element, not the html of the element itself.
If you access the Javascript element from the jQuery array of objects you should get the raw html back. Check out this fiddle: http://jsfiddle.net/NvKYT/
var doneButton = $('<input>', {
type: 'button',
value: 'Done',
click: function() {
alert("Done!");
}
});
//doneButton[0] - your html
Try passing doneButton[0] as that is the actual element, not the jQuery wrapped element.

Categories

Resources