How can I dynamically set id for hidden fields in template file?? I want to display the value in the alert box later using JS.
Template file:
<table>
%for doc in docs:
<tr>
<td>
Link
<input type=hidden id="**do something here**" name="hidden" value="{{doc["Field"]}}" />
</td>
</tr>
%end
</table>
JS:
function popup1()
{
alert(document.getElementById("hiddenFieldID").value);
}
Can anybody suggest me what to do in do something here ???
Perhaps you do not need the ID
If you do
Link
you can have
function popup1(anchor) {
alert(anchor.parentNode.getElementsByTagName("input")[0].value);
return false;
}
In jQuery:
Link
using
$(function() {
$(".popup").on("click",function(e) {
e.preventDefault();
alert($(this).next().val());
});
});
Related
I have a shopping cart that contains a form field and a checkbox in each row. The form field controls the quantity, which can be edited, if the customer wants to modify the quantity of the product they order, and the checkbox selects the item, either to toss the item in a wish list, or to remove it. The Add To Wish list and Remove Functions are separated out of this particular question.
What, I am looking at doing, is detecting when the form has been changed, and then targeting EVERY anchor tag and button on the page, so if the items have been modified, the script stops the click through and pops up a bootstrap modal, alerting the user that something in their cart has been modified.
HTML (the shopping cart row, run through a JSTL forEach loop, but the markup is this):
<table>
<form id="shoppingCart" action="updateTheCart.action">
<c:forEach var="item" items="${shoppingCart.items}" varStatus="status">
<tr class="cart-row">
<td class="remove" data-label="Remove">
<label>
<input type="checkbox" name="removeFlag(<c:out value="${status.count}"/>)" value="true"/>
</label>
</td>
<td class="title" data-label="Title">
${item.value.sellableGood.name}
</td>
<td class="qty" data-label="Quantity">
<input type="num" class="form-control qty-input" name="quantity(<c:out value="${status.count}" />)" value="<c:out value="${item.value.quantity}" />"/>
</td>
<td class="subtotal" data-label="Line Total">
<fmt:formatNumber type="currency" pattern="$#,##0.00" value="${item.value.itemExtendedTotal}" />
</td>
</tr>
</c:foreach>
</table>
<p>Checkout</p>
<p><button type="submit" id="checkout">Update Cart</button></p>
<p><button id="addToWishlist" type="submit" id="wish-list">Add To Wish List</button></p>
<p>Chontinue Shopping</p>
</form>
JS:
$("#shoppingCart :input").change(function() {
$("#shoppingCart").data("changed",true);
});
I know I am missing a LOT, but I really don't know where to begin at this point.
You can try the onbeforeunload Event
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
Javascript:
;[].forEach.call(document.querySelectorAll('a, button'), function(element) {
//do something with buttons and links, for example:
element.setAttribute('data-changed', true')
});
The jquery equivalent is:
$('a, button').each(function(element) {})
To watch the form for changes, I would use the blur event, it's the reverse of focus:
;[].forEach.call(document.querySelectorAll('#myForm input'), function(element) {
element.addEventListener('blur', function(event) {
//something has changed
})
});
Jquery:
$('#myForm input').on('blur', function(event) {})
<td id="RB_0_val_1">
<label for="RB_0_value_field_1" style="display:none;">Field Value</label>
<input type="text" id="RB_0_value_field_1"></td>
<td id="RB_0_extra_1"><input type="button" value="Select.." id="File"></td>
Now i need to find the id of textbox on th click of button.So i am using
var textboxid=$('input[id="File"]').closest('input[type="text"]').attr("id");
but value returned is undefined.
The id of the textbox is auto generated so i need to find the id on the click of the button.
How to do this?
Please replace your code with my code where just add prev() function.
var textboxid=$('input[id="File"]').prev().closest('input[type="text"]').attr("id");
Try utilizing .parentsUntil , :has()
$("#File").click(function() {
var textboxid = $(this).parentsUntil("td:has(:text)").find(":text").attr("id")
console.log(textboxid)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td id="RB_0_val_1">
<label for="RB_0_value_field_1" style="display:none;">Field Value</label>
<input type="text" id="RB_0_value_field_1">
</td>
<td id="RB_0_extra_1">
<input type="button" value="Select.." id="File">
</td>
</tr>
</tbody>
</table>
You can use jquery .prev() api, for doing that. Try the FIDDLE
Javascript code
$(document).ready(function(){
$('#File').click(function(e){
console.log($(this).prev('input[type=text]').prop('id'));
alert($(this).prev('input[type=text]').prop('id'));
e.preventDefault();
});
});
EDIT : For Updated markup provided in FIDDLE, I have used .closest() .prev() and .find() jquery api
$(document).ready(function () {
$('#File').click(function (e) {
var id = $(this).closest('td').prev('td').find('input[type=text]').prop('id');
alert(id);
e.preventDefault();
});
});
Hope this helps .....
I assume that the tds are inside a tr.
You can make this selector
var textboxid=$('input#File').parents('tr').find('label + input').attr("id");
Try this maybe (haven't tried it) :
var textboxid = $('#File').parent().find('input[type=text]').first().attr("id");
Should it be triggered by a click or something ?
Problem is the text box is in different td, try this:
$(function() {
$('#File').on('click', function() {
alert($(this).parent().prev('td').children('input[type=text]').prop('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td id="RB_0_val_1">
<label for="RB_0_value_field_1" style="display:none;">Field Value</label>
<input type="text" id="RB_0_value_field_1">
</td>
<td id="RB_0_extra_1">
<input type="button" value="Select.." id="File">
</td>
</tr>
</table>
FIDDLE
$$(document).on('click', '#File', function() {
var qwe = $(this).parent().parent().find('input[type="text"]');
alert(qwe.attr('id'));
});
I'm refactoring a code on a generated web page and there is a div (tab) which can occur multiple times. There is a small section with check-boxes on each and every such div, which lets you choose other divs that will be shown.
Since there is a chance for other divs to be added to the page I wanted to make the code modular. Meaning that every checkbox id is identical to the class of the div, which it should toggle, with added "Div" at the end. So I use checked id, concat it with "." and "Div" and try to find it in closest fieldset.
Here is the almost working fiddle: http://jsfiddle.net/ebwokLpf/5/ (I can't find the way to make the onchange work)
Here is the code:
$(document).ready(function(){
$(".inChecks").each(function(){
changeDivState($(this));
});
});
function changeDivState(element){
var divClassSel = "." + element.attr("id") + "Div";
var cloField = element.closest("fieldset");
if(element.prop("checked")){
cloField.find(divClassSel).toggle(true);
} else {
cloField.find(divClassSel).toggle(false);
}
}
Aside for that not-working onchange, this functionality does what it's intended to do. However only on the jsfiddle. The same code does not work on my page.
When I used log on variables from the code, the result was as this
console.log(divClassSel) => inRedDiv
console.log($(divClassSel)) => Object[div.etc.]
console.log(cloField) => Object[fieldset.etc.]
//but
console.log(cloField.find(divClassSel)) => Object[]
According to firebug the version of the jQuery is 1.7.1
Since I can't find any solution to this is there any other way how to make it in modular manner? Or is there some mistake I'm not aware of? I'm trying to avoid writing a function with x checks for element id, or unique functions for every check-box (the way it was done before).
Remove the inline onchange and also you don't need to iterate on the elements.
Just write one event on class "inCheckes" and pass the current element reference to your function:
HTML:
<fieldset id="field1">
<legend>Fieldset 1</legend>
<table class="gridtable">
<tr>
<td>
<input id="inRed" class="inChecks" type="checkbox" checked="checked" />
</td>
<td>Red</td>
</tr>
<tr>
<td>
<input id="inBlue" class="inChecks" type="checkbox" />
</td>
<td>Blue</td>
</tr>
</table>
<div class="inDivs">
<div class="inRedDiv redDiv"></div>
<div class="inBlueDiv blueDiv" /></div>
</fieldset>
<fieldset id="field2">
<legend>Fieldset 2</legend>
<table class="gridtable">
<tr>
<td>
<input id="inRed" class="inChecks" type="checkbox" />
</td>
<td>Red</td>
</tr>
<tr>
<td>
<input id="inBlue" class="inChecks" type="checkbox" checked="checked" />
</td>
<td>Blue</td>
</tr>
</table>
<div class="inDivs">
<div class="inRedDiv redDiv"></div>
<div class="inBlueDiv blueDiv" /></div>
</fieldset>
JQUERY:
$(document).ready(function () {
$(".inChecks").change(function () {
changeDivState($(this));
})
});
FIDDLE:
http://jsfiddle.net/ebwokLpf/4/
As gillesc said in the comments changing the javascript code to something like this made it work.
$(document).ready(function(){
$(".inChecks").each(function(){
changeDivState($(this));
});
$(".inChecks").on("change", function() {
changeDivState($(this));
});
});
function changeDivState(element){
var divClassSel = "." + element.attr("id") + "Div";
var cloField = element.closest("fieldset");
if(element.prop("checked")){
cloField.find(divClassSel).toggle(true);
} else {
cloField.find(divClassSel).toggle(false);
}
}
You asked for an other way how to make it in modular manner:
You can create a jQuery plugin which handles the logic for one fieldset including changing the color when clicking different checkboxes.
This way all logic is bundled in one place (in the plugin) and you can refine it later on.
For example you can decide later on that the plugin should create the whole html structure of the fieldset (like jQuery UI slider plugin creates the whole structure for the slider element) and therefore change the plugin.
The code for the (first version) of your jQuery plugin could look something like this:
$.fn.colorField = function() {
var $colorDiv = this.find('.colorDiv'),
$inputs = this.find('input'),
$checked = $inputs.filter(':checked');
if($checked.length) {
// set initial color
$colorDiv.css('background', $checked.attr('data-color'));
}
$inputs.change(function() {
var $this = $(this),
background = '#999'; // the default color
if($this.prop('checked')) {
// uncheck the other checkboxes
$inputs.not(this).prop('checked', false);
// read the color for this checkbox
background = $(this).attr('data-color');
}
// change the color of the colorDiv container
$colorDiv.css('background', background);
});
};
The plugin uses the data-color-attributes of the checkboxes to change the color of the colorDiv container. So every checkbox needs an data-color attribute, but multiple divs for different colors are not necessary anymore.
The HTML code (for one fieldset):
<fieldset id="field1">
<legend>Fieldset 1</legend>
<table class="gridtable">
<tr><td><input id="inRed" class="inChecks" type="checkbox" checked="checked" data-color='#ff1005' /></td><td>Red</td></tr>
<tr><td><input id="inBlue" class="inChecks" type="checkbox" data-color='#00adff' /></td><td>Blue</td></tr>
</table>
<div class="colorDiv"></div>
</fieldset>
Now you can create instances with your colorField-plugin like this:
$(document).ready(function(){
$('#field1').colorField();
$('#field2').colorField();
});
Here is a working jsFiddle-demo
I have a list of users that in the end of each line in the table I added two links("href"):
one for "update" user and secend for "delete" user.
So for enable that I added a call to javascript function that capture the ID of user
and insert it to some form that I created before (form with only one "hidden" field),
and then the function activated submit() operation to the server part (asp.net code).
I checked and the submit() operation works ok(checked with respons.write()...)
But I know how to recognize a submit form button inside IsPost by ask what the value
of the submit button (for example: if(Request.Form["ExpertButton"]== "delete"){..some code here....})
But when I activate submit() with javascript, how could I recognize post?
I tryed with the value of the hiiden field but it's not capture this
and it skiped of the if statement....
the list of users code:
foreach(var row in db.Query(displayExperts,nameOfExpert))
{
<tr>
<td class="dispExpertActScreen">#row.ExpertID</td>
<td class="dispExpertActScreen">#row.name</td>
<td class="dispExpertActScreen">#row.password</td>
<td class="dispExpertActScreen">#row.allowBonds</td>
<td class="dispExpertActScreen">#row.allowStocks</td>
<td class="dispExpertActScreen">#row.allowExchangeTraded</td>
<td class="dispExpertActScreen">#row.allowMutualFund</td>
<td class="dispExpertActScreen">update</td>
<td class="dispExpertActScreen">delete</td>
</tr>
}
the form code:
<form method="post" name="deleteExpert" style="font-size: medium; margin-top: 10%" dir="rtl">
<input type="hidden" name="expertID" id="expertID" value="">
</form>
the javascript code:
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('deleteExpert').submit ();
}
</script>
the asp.net code:
#{
var db = Database.Open("MyProjectSite");
var display="no";
var displayExperts="";
var nameOfExpert="";
var category="";
if(IsPost)
{
if(Request.Form["ExpertButton"]== "search")// this is by button!!!
{
some code.....
}
//Response.Write("^^^^^^^^^^^^^^^^^^^^^");
if(Request.Form["ExpertButton"] != "")// this need to be by javascript submit() method !!! here I need to recognize it.
{
var id=Request.Form["expertID"];
Response.Write("^^^^^^^^^^^^^^^^^^^^^"+id);
var deleteQuery="DELETE FROM InvestmanExperts WHERE ExpertID=#0";
db.Execute(deleteQuery,id);
}
}
db.Close();
}
thanks...
Why not puting another hidden input value :
<input type="hidden" name="txtJavascriptMode" id="txtJavascriptMode" value="">
then in your javascript code :
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('txtJavascriptMode').value = 'true';
document.getElementById('deleteExpert').submit ();
}
</script>
and in your serverside you can checkout
if(Request["txtJavascriptMode"] == "true")
{}
In this jsfiddle
http://jsfiddle.net/littlesandra88/eGRRb/
have I submit buttons that are auto-generated. Each table row gets an unique ID number, and if needed each submit button can get the same unique number as well.
Question
The problem is that there are multiple submit buttons, so how do I know which was pressed?
HTML
<form action="" method="post">
<table class="alerts tablesorter" id="accTable" cellspacing="0">
<thead>
<tr class="header">
<th class="activity-header"> A </th>
<th class="activity-header"> Signed </th>
<th class="activity-header"> </th>
</tr>
</thead>
<tbody>
<tr class="row" id="7249">
<td class="activity-data">7249</td>
<!-- tablesorter can't sort a column with check boxes out-of-the-box, so it needs something to sort on. That is why the span tag is here -->
<!-- a jquery script is watching the state of the checkbox, so when clicked the value in the span is updated -->
<td class="checkbox"> <span style="display:none;">0</span> <input name="signed" type="checkbox" > </td>
<td class="edit-column"> <input value="Save" type="submit" name="7249"></td>
</tr>
<tr class="row" id="61484">
<td class="activity-data">61484</td>
<td class="checkbox"> <span style="display:none;">1</span> <input name="signed" type="checkbox" checked > </td>
<td class="edit-column"> <input value="Save" type="submit" name="61484"></td>
</tr>
</tbody>
</table>
</form>
JavaScript
$(document).ready(function() {
$("#accTable").tablesorter();
// :checkbox stops from executing the event on the save button. Same as input[type=checkbox]
$('#accTable input:checkbox').click(function() {
// insert 1 or 0 depending of checkbox state in the tag before the input tag. In this case <span> is before <input>
// this is done so tablesorter have something to sort on, as it doesn't support checkbox sort out of the box.
var order = this.checked ? '1' : '0';
$(this).prev().html(order);
$(this).parents("table").trigger("update");
});
});
// sends the form content to server side, and stay on page
$('form').live('submit', function() {
alert('test');
// don't redirect
return false;
});
You could use delegate():
$('form').delegate('input:submit','click',
function(){
alert(this.name);
return false;
});
JS Fiddle demo.
Edited to address question in the comments, from OP:
Would it be possible to display 0 or 1 as the state of the associated checkbox with this approach?
Yeah, that's possible, though it's a little more long-winded than I'd like:
$('form').delegate('input:submit','click',
function(){
var idString = this.name;
var checkboxState = $('#' + idString).find('input:checkbox').is(':checked');
if (checkboxState == true){
alert('1');
}
else {
alert('0');
}
return false;
});
JS Fiddle demo.
You will need to add an onClick handler to each button that does:
$(this).closest('form').data('submit_name', this.name);
Assign a function to the click event of the submit buttons. That function should simply store the clicked button's value in a variable. Inside the submit event of the form, check the value of that variable. The submit event will fire after the click event so you should be able to get the expected result.
Demo here
The thing to note here is that that different browsers behave differently when dealing with multiple submit buttons; specially when you hit enter to submit the form. I think my example takes care of this.
As you are using one form and using $('form').live('submit', function() { and both submit buttons are in the same form so its not possible in submit event. You have to use click event or two form tags.
Here is how I solve this,
HTML
<form id="my-form" ...>
....
Save
Save and add another
</form>
Javascript
$('.btn-submit-form').on('click', function(ev){
ev.preventDefault();
var $form = $(this).attr('href');
if ($form.length > 0) {
$form.trigger('submit', {'submitBtn': $this});
}
});
$('form').on('submit', function(ev, extra) {
if (extra && extra.submitBtn) {
var submitVal = extra.submitBtn.attr('data-value');
} else {
var submitVal = null;
}
// submit the form as you want with submitVal as one of the fields.
});
The advantage here is that your form only submits on the submit event and not on click event. This way you can have one common function to submit the form whether you click a button, hit return in a form field or submit it pragmatically.
I also like to make things as generic as possible and turn them into patterns. This two functions can work across your whole project if you come up with some patterns like naming each submit button with value as .btn-form-submit and having a data-value attribute to store the value.