disable dynamic id buttons with jQuery - javascript

I'm using VB.Net, MVC 5, razor and jQuery. I have a razor view that creates buttons I'm trying to disable on the user click. I generally accomplish this task using jQuery:
$('#id').prop("disabled", true);
My task is new to me in that my buttons are generated like this:
#For i As Integer = 0 To Model.hrmnValues.Count - 1
#<div class="col-md-3">
<a class="btn btn-primary btn-md" href="#" id="#Model.inventoryCategoryAttIDs(i)"
onclick="acceptChange('#Model.hrmnValues(i)',
#Model.inventoryCategoryAttIDs(i), #Model.uniqueItemID)">Accept Change</a>
</div>
Next
My onClick function is similar to this:
function acceptChange(newValue, categoryAttID, itemID) {
$('#categoryAttID').prop("disabled", true);
}
This obviously does not work, as it is looking for an id with the name of categoryAttID. I have also tried putting the categoryAttID into it's own variable like this:
var idToDisable = "#" + categoryAttID;
and then putting idToDisable into the jQuery call to disable the button, this did not work.
Given this situation how can I disable the button that is clicked?
There will be multiple buttons on this page making use of the function, the function actually performs an ajax call. The idea is to limit the user to performing one ajax call per button.
The html is rendered like this:
<div class="row">
<div class="col-md-3">
<font>First Name</font>
</div>
<div class="col-md-3">
<font>John</font>
</div>
<div class="col-md-3">
<font>No Record Found</font>
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-md" href="#" id="2"
onclick="acceptChange('CHRISTOPHER', 2, 0)">Accept Change</a>
</div>
</div>
<div class="row">
<div class="col-md-3">
<font>Last Name</font>
</div>
<div class="col-md-3">
<font>MURRAY</font>
</div>
<div class="col-md-3">
<font>No Record Found</font>
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-md" href="#" id="3"
onclick="acceptChange('MURRAY', 3, 0)">Accept Change</a>
</div>

You're already passing the button's id to your function as the second argument -
acceptChange('#Model.hrmnValues(i)',#Model.inventoryCategoryAttIDs(i), #Model.uniqueItemID)
So you can change your function to -
function acceptChange(newValue, categoryAttID, itemID) {
$('#' + categoryAttID).prop("disabled", true);
}
Also, there isn't a disabled property available for links (see - Mozilla Developer Network) if you want to disable your elements on click try using a button instead.
Since you appear to be using bootstrap after changing your links to buttons you might want to change your function to -
function acceptChange(newValue, categoryAttID, itemID) {
$('#' + categoryAttID).prop("disabled", true);
$('#' + categoryAttID).addClass("disabled");
}

Related

in meteor how to stop functionalities to work at a time?

In meteor, I have created a cards dynamically after submitting the form. and the dynamic card contains the show and hide buttons. When I click on show option button the hidden part is showing for all the cards instead of that particular card. the problem is the card is creating dynamically so I thought that is problem .. how to make the functionality to work separately to the each card.
Here I am attaching the code:
<div id="newActionCard">
{{#each newaction}}
<div class="workflowcard">
<div class="module-card">
<div class="res-border"></div>
<div class="card-img"></div>
<div class="res-content">
<div class=" assigned-team">{{team}}</div>
<div class=" newaction-name">{{action_title}}</div><hr>
<div class="description">{{description}}</div>
<div class=" due-on">Due on:{{d_date}}</div><hr>
<div class="subcontent">
{{> actioncardsubcontent}}
</div>
<div class="reqext">
{{> requestextensioncard}}
</div>
</div>
<div class="due">
Due on:
<div>
<span class="day-stamp">THU</span><br>
<div class="date-stamp">26</div>
<div class="month-stamp">AUG
</div>
</div>
</div>
</div>
<div class="btn-box newaction">
<button type="button" class="cancelsub" >New Action</button>
<button type="submit" class="createbtnsub" >Show Options</button>
</div>
<div class="btn-box showoption">
<button type="button" class="hideoption" style="display:none">Hide Options</button>
</div>
{{/each}}
</div>
In JS I have written the hide and show functionalities in the events..now how to stop functionality to all cards at a time.
Here is my JS:
Template.workflow.events({
"click .createbtnsub" : function() {
$( ".subcontent" ).show();
$('.createbtnsub').hide();
$('.cancelsub').hide();
$('.hideoption').show();
$('.requestextension').show();
},
"click .hideoption": function(){
$('.subcontent').hide();
},
"click .hideoption": function(){
$(".subcontent").hide();
$('.cancelsub').show();
$('.createbtnsub').show();
$('.requestextension').hide();
$('.hideoption').hide();
$('.reqext').hide();
},
"click #createActionBtn": function(){
$('#createAction').hide();
$('.editw').show();
$('.hidew').show();
},
});
Template.actioncardsubcontent.rendered = function(){
this.$(".subcontent").hide();
};
Template.requestextensioncard.rendered = function(){
this.$(".reqext").hide();
};
Template.workflow.helpers({
getWorkflow: function(){
return Workflow.find();
},
user: function(){
return Meteor.users.find({});
},
getNewaction: function(){
return Newaction.find();
},
});
Please see the following and adjust the selectors as needed:
"click .showoption": function(event){
$(event.currentTarget).next('button').show();
}
This will work for selecting sibling elements, however as a tip I would recommend rewriting your template.helper that returns the cards data from the database into something more specific.
Something like dynamic classes based on index or id so your class/id names would return as follows .showoption-12kjddfse4 . Then you can just get the attribute of the current target and apply it to your js selector.
Also as kind of an explination to why all buttons were showing, is you were using the class selector, which is meant for grabbing groups of elements/nodes. This is also another reason to created more specific classnames/ids to your use case.
So in your class name you could do something like
<button class="showoption" id="{{_id}}">button</button>
<button id="hiddenoption-{{_id}}" class="hiddenoption">button</button>
Then selecting your elements would be easier as follows:
'click .showoption'(event) => {
let id = event.currentTarget.getAttribute(id);
document.getElementById('hiddenoption-'+id).style.display = 'block';
}

Ui-router, ng-repeat and ui state

I m developping an application in which I need to redirect the current user to a different state after a ressource creation.
Actually, I have a list of demands, and I need to show or create a quotation based on that demand.
Here's the view code :
<div class="landing-diags">
<div class="current-projects">
<div class="row project-summary" ng-repeat="demand in landingdiag.demandsList">
<div class="col-md-2 project-block first-block {{project.projectType}}">
<p class="project-strong">{{demand.user.firstname}} {{demand.user.lastname}}</p>
</div>
<div class="col-md-2 project-block">
<p class="project-strong">{{demand.creationDate | date:"dd/MM/yyyy"}}</p>
</div>
<div class="col-md-4">
</div>
<div class="col-md-2">
<div ng-if="!demand.quotation">
<button ng-click="landingdiag.createQuotation(demand)" class="btn btn-primary pull-right bar-btn">Create</button>
</div>
<div ng-if="demand.quotation">
<button ui-sref="app.state.concerned({id: demand._id})" class="btn btn-primary pull-right bar-btn">Show</button>
</div>
</div>
</div>
</div>
</div>
And here's the controller methods implied :
createQuotation (demand) {
this.DemandsService.createQuotation(demand).$promise.then((response) => {
this.redirectToQuote(demand);
});
}
redirectToQuote (demand) {
this.$state.transitionTo('app.state.concerned', {id: demand._id});
}
Problem
My problem is that I m never redirected when creating a quotation. If I console log the redirectToQuote method, I pass inside of it. So it seems that my problem is on the $state.go call.
However, when I try to redirect directly using the redirectToQuote method inside of my view on the "show" button like following :
<div ng-if="demand.quotation">
<button ng-click="landingdiag.redirectToQuote(demand)" class="btn btn-primary pull-right bar-btn">Accéder au devis</button>
</div>
I m well redirected to the concerned state
I am concerned about the this.redirectToQuote within createQuotation() which is called by then() as a callback. So the this object will definitely not be your controller.
Look at the first code snippet from todd: https://toddmotto.com/resolve-promises-in-angular-routes/
He is using bind.
You can also look at https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes from awesome Kyle Simpson
or shorter from myself: http://blog.monkey-development.com/javascript/java/2015/12/18/javascript-this.html

passing as parameter the value of a component html

Maybe is my question trivial, but I could not found a answer. Maybe I have been to much hours in front of the monitor :)
I have this situation:
<div class="col-xs-3" style='margin-left: -50px;'>
<a class="btn btn-primary" href="?c=Student&a=list" id="protokol"> List Studens</a>
</div>
This represent a button and with the click event, using MVC, the controller Student is called and the function list executed. But I need to send a parameter to this function that is the value of a HTML component.
<input type='text' id='parm' value=''>
How I can do this using the same structure? I tryed this, but is not correct
<div class="col-xs-3" style='margin-left: -50px;'>
<a class="btn btn-primary" href="?c=Student&a=list&v=<script>$('param').val();</script>" id="protokol"> List Studens</a>
</div>
If you're using jQuery you can attach a click handler to that element which appends the current value of the input. Try this:
$(function() {
$('#protokol').click(function(e) {
e.preventDefault(); // prevent the browser going to the default URL
var url = $(this).attr('href') + '&v=' + $('#param').val();
window.location.assign(url);
});
});
try this instead
<div class="col-xs-3" style='margin-left: -50px;'>
<a id="targetLink" class="btn btn-primary" href="?c=Student&a=list&v=<script></script>" id="protokol"> List Studens</a>
</div>
//document ready
$(function(){
var parameter = $('param').val();
$('#targetLink').attr('href', '?c=Student&a=list&v=' + parameter);
});

how to use javascript event handler

I have a 2 col layout, on the left i have a button that says show code and on the right i have some html.
The above is repeat numerous time so i have a list of buttons that i want related to the "widget" next to it.
If i click on each button, i would like to show the innerHTML of the element to the right in an alert box.
My right column html widgets are a class called "mywidgets", and my buttons to the left have a class called "showcode"
how would I go about showing the code of the related box to the right on click of button to the left in javascript or jquery?
if I do something like:
var showthem = document.getElementsByClassName('mywidgets');
for (var i=0; i < widgetBits.length; i++) {
};
but I get confused on how to count each button and each class in the seperate area, then show the code on click.
I was also thinking about something similar to below but again I get confused on how to utilize "this"/each item clicked.
$(document).ready(function(){
$("button").click(function(){
$("mywidgets").clone().appendTo("myareofchoce");
});
});
HTML:
left area :
<div class="container marginBTM10">
<div class="row">
<div class="col-lg-offset-2 col-md-offset-2 col-lg-10 col-md-10 bgColor_FFF padding10">
<h2>Widget 1</h2>
<div class="highlight">
<button class="btn btn-primary btn-sm " onclick="widgets()">get code</button>
right hand area :
<div class="col-lg-4 col-md-4">
<!-- widget 1 starts-->
<div class="sortable bgColor_FFF mywidgets">
<div class="padding10">
stuff
</div>
</div>
<!-- widget 1 ends-->
</div>
</div>
http://jsfiddle.net/wne6rnda/1/
to connect buttons and widgets must be used in a single tag.
in this case: widget has id and corresponding button has data-id with same value
HTML:
buttons:
<button class="btn btn-primary btn-sm get_class" data-id="#mywidgets1">
...
<button class="btn btn-primary btn-sm get_class" data-id="#mywidgets2">
...
widgets:
div class="sortable bgColor_FFF mywidgets" id="mywidgets1">
...
div class="sortable bgColor_FFF mywidgets" id="mywidgets2">
...
JQ
$('.get_class').click(function () {
//get id of selected widget
var id = $(this).data('id');
//get selected widget
var $widget = $(id);
//clon and add selected widget
$widget.clone().appendTo(".myareofchoce");
})
UPDATE: 2
http://jsfiddle.net/wne6rnda/9/
$('.get_class').click(function () {
var id = $(this).data('id');
var $widget = $(id);
var html=$widget.html();
//solution 1 - output to the textarea
var txt=$(".myareofchoce2").val();
$(".myareofchoce2").val(txt+"\r\n"+html);
//solution 2 - use <xmp> tag
html='<xmp >'+html+'</xmp >';
$(".myareofchoce").append(html);
})

Modal Form Submission without refresh

I have a modal window that pops up when I want to add a new project to my dashboard. I have gotten it to work with jquery post however, I cannot prevent it from refreshing. What I want to do is after the project is added to the database, show a success message and close the modal window after few seconds and not refresh the page (parent page of modal).
Here is my modal
<div class="modal fade" id="add-project-dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Add a new Project</h4>
</div>
<div class="modal-body">
<h3>New Project:</h3>
<form class="form-horizontal" id="add-project-form" action="/projects/add" method="POST">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Project Name</label>
<div class="col-md-4">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="description">Project Description</label>
<div class="col-md-4">
<input id="description" name="description" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="project_state">Project State</label>
<div class="col-md-4">
<input id="project_state" name="project_state" type="text" placeholder="" class="form-control input-md">
</div>
</div>
</fieldset>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add-btn" class="btn" type="submit">Add</button>
</div>
</form>
</div>
</div>
Here is my project-dashboard.js
AddProject = function(){
$(document).ready(function() {
$("#submit").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
}
My views.py
class AddProject(webapp2.RedirectHandler):
def get(self):
template_values = {
#'greetings': greetings,
#'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), '../templates/project-add.html')
self.response.write(template.render(path, template_values))
def post(self):
project = Project()
project.name = self.request.get('name')
project.description = self.request.get('description')
project.project_state = self.request.get('project_state')
time.sleep(2)
project.put()
self.redirect('/projects')
I have tried removing the self.redirect('/projects') however that only takes me to a blank page that is /projects/add (that is the action in the form).
The issue is that you added .ready(foo) handler inside of the AddProject function. I suppose that document is loaded when AddProject is called.
Another issue is that in your HTML, the form has id add-project-form, so you should do $("#add-project-form") instead of $("#submit").
$(document).ready(function () {
$("#add-project-form").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
});
Take ready handler outside of the AddProject function and it should work (the submit handler is added).
Edit: After some debugging, the answer was to use the right id and proper placing of the javascript code, as noted by the comments.
For starters, a refresh is easy to avoid, just make sure to prevent the default event from running; since you're using jQuery, I would recommend doing return false to end the function, since it both 'prevents default' and 'stops propagation'.
So the first thing you should do is check if your javascript code is actually running and not erring in the middle of execution. If everything is fine there, the worst case is that the project is not actually added (server side error) but the page should not refresh.
Your server side code has nothing to do with the refresh (if it's being properly hijacked), so the response doesn't really matter, I would actually return the id of the new project (so you could provide a link for the newly created item or something like that), but i digress...
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok")) //custom validation dont copy
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular class button
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Now you should get no page refreshes on any of your modals if u follow these steps.

Categories

Resources