using one one event for multiple purpose - javascript

I have buttons like this :
<input class="btnRating" type="button" value="Project Rate" />
<input class="btnRating" type="button" value=" Education Rate" />
<input class="btnRating" type="button" value="Achievement Rate" />
i want to use 3 buttons as per different click ,different purpose
and in one event i want to write like this :
// Event For Open Modal Pop for rating
$('.btnRating').on("click", function (ele) {
if(thisbutton ==Project )
{
// do something for project related
}
if(thisbutton ==Education)
{
// do something for Education related
}
if(thisbutton ==Achievement)
{
// do something for project related
}
});
how do i write event like this?

If clicking each button has completely different consequences
It's more logical if they are handled by different events. Different meaning they don't share most of their code. Even if you don't want to write three events (why? it's the same amount of lines of codes), it fits better the use case.
If clicking each button has similar consequences
This seems to be your case, since all buttons have "Rate" in their name. If so, you are right that you should only have one event, since most of the code will be the same. However, instead of using different code paths (if/else or switches), it's better if you add a data- attribute to your buttons to so that, by using the value in those attributes, the same code can behave in different ways. Let's say the only difference between them is a "Rate Multiplier". You could do this:
<input type="text" id="costToMultiplyByRate" />
<input class="btnRating" type="button" value="Project Rate" data-rate="5" />
<input class="btnRating" type="button" value=" Education Rate" data-rate="4" />
<input class="btnRating" type="button" value="Achievement Rate" data-rate="10" />
$('.btnRating').on("click", function (ele) {
var rate = ele.getAttribute("data-rate");
var cost = document.getElementById("costToMultiplyByRate");
alert(rate * cost);
}
However, if by adding only one or two data attributes you can't make the three buttons use exactly the same code, I suggest you use multiple events.

Try
$('.btnRating').on("click", function (ele) {
if (this.value.indexOf('Project') > -1) {
// do something for project related
} else if (this.value.indexOf('Education') > -1) {
// do something for Education related
} else if (this.value.indexOf('Achievement') > -1) {
// do something for project related
}
});

You can test the value of the cbutton
$('.btnRating').on("click", function (ele) {
if (this.value == 'Project Rate') {
// do something for project related
} else if (this.value == ' Education Rate') {
// do something for Education related
} else if (this.value == 'Achievement Rate') {
// do something for project related
}
});
Better solution is to have a unique selector for the buttons and write separate handlers for each one

Try:
$('.btnRating').on("click", function (ele) {
var val = $(this).val();
if(val == "Project Rate"){
}
else if(val == " Education Rate"){
}
else if(val == "Achievement Rate"){
}
});

I recommend add classes to buttons
<input class="btnRating project" type="button" value="Project Rate" />
<input class="btnRating education" type="button" value=" Education Rate" />
<input class="btnRating Achievement" type="button" value="Achievement Rate" />
And then use separated events
$('.btnRating.project').on("click", function (ele) {
// do something for project related
});

add attribute : data-event
<input class="btnRating" type="button" value="Project Rate" data-event="project" />
then u can use a switch
$('.btnRating').on("click", function (ele) {
switch($(this).data("event")) {
case "project" :
//fire your function
break;
}
}

Can you please try this,
In HTML section:
<input class="btnRating" id="ProjectRate" type="button" value="Project Rate" />
<input class="btnRating" id="EducationRate" type="button" value=" Education Rate" />
<input class="btnRating" id="AchievementRate" type="button" value="Achievement Rate" />
In Script:
<script>
$(function(){
// Event For Open Modal Pop for rating
$('.btnRating').click(function (ele) {
var thisbutton = $(this).attr('id');
if(thisbutton =="ProjectRate")
{
// do something for project related
}else if(thisbutton =="EducationRate")
{
// do something for Education related
}else if(thisbutton =="AchievementRate")
{
// do something for project related
}else{
// do your default
}
});
});
</script>

<input class="btnRating" type="button" data-action="project" value="Project Rate" />
<input class="btnRating" type="button" data-action="education" value=" Education Rate" />
<input class="btnRating" type="button" data-action="achievement" value="Achievement Rate" />
$(".btnRating").click(function () {
var action = $(this).attr("data-action");
if (action === "project") {
// do project
} else if (action === "education") {
// do education
}
});
This way you can have any value (text) on the button, which is good if you want to globalize your website in the future.

$('.btnRating').click(function (ele) {
if($(this).val()=="Project Rate" )
{
// do something for project related
}
else if($(this).val() =="Education Rate")
{
// do something for Education related
}
else if($(this).val() =="Achievement Rate")
{
// do something for project related
}
});
Demo here http://jsfiddle.net/3Mf3j/

Try this:
$('.btnRating').on("click", function (ele) {
var value = $(this).val();
if(value.indexOf("Project Rate") != -1)
{
// do something
}
else if(value.indexOf("Education Rate") != -1)
{
// do something
}
else if(value.indexOf("Achievement Rate") != -1)
{
// do something
}
});

Use event.delegate http://api.jquery.com/delegate/ - something like http://jsfiddle.net/aamir/zw27q/2/
I will recommend that use unique css classes for each buttons as if you change the Value of each input than you have to change your JS as well. So instead of checking for val=='Project Rate you should check for $this.hasClass('rateProj')
$(".btns").delegate("input", "click", function () {
var $this = $(this),
val = $this.val();
if (val =='Project Rate') {
//code
}
//more if statements
});

I suggest you use data-attribute to achieve this. as comparing string can cause more time for checking...
I have created jsfiddle for this.
http://jsfiddle.net/x4yyp/2/
$(document).on("click", ".btnRating", function () {
var optionValue = $(this).data("optionvalue");
if(optionValue == 1)
{
alert("hello");
}
else if(optionValue == 2)
{
alert("your name");
}
else if(optionValue == 3)
{
alert("your email");
}
});

this will help you
$(document).ready(function(e) {
$('.btnRating').on("click", function (ele) {
var btnType = $(this).val();
switch(btnType) {
case 'Project Rate':
// your action;
break;
case ' Education Rate':
// your action;
break;
case 'Achievement Rate':
// your action;
break;
}
});
});

Related

jQuery - radio button on click and not on change

I'm trying to find a solution to an issue I have between click and change.
I need to capture the click event and not change.
I'll explain the situation:
I have a radio button list with 3 items.
Each click I need to clean a div. However, If i'm posting back and return to the client with an error(submit, server validation check failed), the change event is fired once again (obviously), and the div is cleaned.
Is there a way to distinguish between click and the checked state?
I hope I have made myself clear.
Edit:
Added some code:
$("input[name*='SelectedOwner']").on('change',
function () {
var radioId = $(this).val();
if (radioId === "2" || radioId === "3") {
$("#div1").hide();
$("#divclean :input").removeAttr("disabled");
} else {
$("#div1").show();
$("#divclean :input").attr("disabled", true);
}
});
$("input[name*='SelectedOwner']").on('click', function () {
//Clean the output at each change
$("#divclean :input").val("");
});
Thanks.
$('input[name="choose"]').click(function(e) {
if ($(this).data('clicked')) {
$('#theDiv').text('You have REclicked "'+ $(this).val() + '" value');
}
else {
$('input[name="choose"]').data('clicked', false);
$(this).data('clicked', true);
$('#theDiv').text('First time you click "'+ $(this).val() + '" value');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theDiv"></div>
A
<input type="radio" name="choose" value="a" />
B
<input type="radio" name="choose" value="b" />
C
<input type="radio" name="choose" value="c" />
You should to bind the change event to every radio button:
$("#r1, #r2, #r3").change(function () { }
With jQuery is also possible:
if ($("#r1").is(":checked")) {}
More informations:
JQuery $(#radioButton).change(...) not firing during de-selection
I hope this helps...
Good Luck!

Popups for checking/unchecking a checkbox

I have prompts that produce a popup when a box is ticked and unticked. There looks to be a line of redundant code, but when removed the functions no longer work. So maybe not so redundant:-) But the #id doesn't match to anything (currently set as CAPS to not match)
Any ideas why this is interfering?
$('#checkbox').click(function() {
if ($("#checkbox").is(':checked')) {
if (confirm('Are you sure you want to CONFIRM the order?')) {
$('#CHECKBOX').click();
}
}
});
$("#checkbox").on('change', function() {
this.checked = !this.checked ? !confirm('Do you really want to change this to NOT RECEIVED?') : true;
});
http://jsfiddle.net/5nd1wj54/1/
Here is what I think you mean
$('#checkbox').click(function() {
if (this.checked) {
this.checked = confirm('Are you sure you want to CONFIRM the order?'));
}
else {
this.checked = !confirm('Do you really want to change this to NOT RECEIVED?');
}
});
Use classes instead ids, so now redundant code needed. You can store informations in the data attribute of a HTML element. jsFiddle.
I've add a class to every checkbox what should be examined.
$(".checkIt").on('change', function() {
if ($(this).is(':checked')) {
confirm('Do you really want to change ' + $(this).data('id') + ' to NOT RECEIVED?');
}
});
HTML
<input type="checkbox" data-id="checkbox1" class="checkIt" />
<input type="checkbox" data-id="checkbox2" class="checkIt" />
<input type="checkbox" data-id="checkbox3" class="checkIt" />

Jquery - a way to reuse same code multiple times

I have some JS functions that looks like :
$('#div1 input[type=radio]').change(function() {
if(this.value=='YES'){
$('#field1').show();
}else{
$('#field1').hide();
}
});
$('#div2 input[type=radio]').change(function() {
if(this.value=='YES'){
$('#field2').show();
}else{
$('#field2').hide();
}
});
$('#div3 input[type=radio]').change(function() {
if(this.value=='YES'){
$('#field3').show();
}else{
$('#field3').hide();
}
});
As they are much similars, there is a way to improve them in less code?
Thanks
The easiest solution is the following. I replaced the if-else hide/show with toggle. I also used === for true type/value comparison.
function changeToggle(inputSelector, fieldSelector, value) {
$(inputSelector).change(function() {
$(fieldSelector).toggle(this.value === value);
});
}
changeToggle('#div1 input[type=radio]', '#field1', 'YES');
changeToggle('#div2 input[type=radio]', '#field2', 'YES');
changeToggle('#div3 input[type=radio]', '#field3', 'YES');
Using a Loop
$("*[id^='div']").each(function(index, div) {
var id = $(div).attr('id').match(/^\w+(\d+)$/)[1];
$(div).find('input[type=radio]').change(function(e) {
$('#field' + id).toggle(this.value === 'YES');
});
});
Try using attribute begins with selector, .closest(), String.prototype.replace() with RegExp /\D/g to match digits in id of closest element where id begins with "div"
$("[id^=div] input[type=radio]").change(function() {
var n = $(this).closest("[id^=div]")[0].id.replace(/\D/g, "");
if (this.value=="YES") {
$("#field" + n).show();
} else {
$("#field" + n).hide();
}
});
Using custom attributes is much better way or if you're in HTML 5 you can use data-attributes. See example below:
<input type="radio" data-show="#field1" />
<input type="text" id="field1" />
<input type="radio" data-show="#field2" />
<input type="text" id="field2" />
<input type="radio" data-show="#field3" />
<input type="text" id="field3" />
JS:
$('input[type=radio]').change(function() {
var targetEl = $(this).data('show');
if($(this).is(':checked')) {
$(targetEl).show();
}else {
$(targetEl).hide();
}
});

Enable/disable button based on accepting the 2 checkbox conditions

I have gone through the stackoverflow regarding enable/disable button conditionally and was able to find some help but NOT EXACT what I was looking for.
Instead of 1 checkbox condition, I have 2 checkbox conditions. So unless if the two checkboxes have been accepted, the button should not be enabled.
Following is my html:
<input type="checkbox" id="f_agree" value="1" onchange="checked(this, 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checked('f_agree', this)"/>
<button type="submit" disabled="disabled" id="acceptbtn">Continue</button>
Following is javascript:
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.disabled = "";
} else {
myLayer.class = "button:disabled";
myLayer.disabled = "disabled";
};
}
I have tried like above, but it is not working. I don't know where I am going wrong.
it won't work because you are not removing that attribute disabled.
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
Update
use any other name then checked as it seems to be reserved and not working.
you also need to do getElementById for element1 and element2.
function checkedFunc(element1Id, element2Id) {
var myLayer = document.getElementById('acceptbtn');
var element1 = document.getElementById(element1Id);
var element2 = document.getElementById(element2Id);
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
<input type="checkbox" id="f_agree" value="1" onchange="checkedFunc('f_agree', 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checkedFunc('f_agree','f_agree2')"/>
<input type="button" value="check" id="acceptbtn" />
You can try the following code
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
With jQuery:
var btn;
var changed = function() {
//get the length of non checked boxes
var disbl = $('input[id^=f_agree]:not(:checked)').length;
btn.prop('disabled', disbl);//disable if true, else enable
};
$(function() {
btn = $('#acceptbtn');
$('input[id^=f_agree]').on('change', changed).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="f_agree" value="1" />1
<input type="checkbox" id="f_agree2" value="1" />2
<input type="button" id="acceptbtn" value="Submit" />
The problem is that there is a difference between the string "f_agree" and the node with id="f_agree".
Your code should work as expected with
checked(this, document.getObjectById('f_agree2'))
Much better would be however to avoid having a widget knowing about the other... I'd implement instead by adding a list of external rules that check all widgets:
function okSubmit() {
return (document.getElementById("f_agree").checked &&
document.getElementById("f_agree2").checked);
}
This is much easier to read/maintain and also scales better in case you need to add more conditions later. In the onchange of all the widgets just call a function that will enable/disable the submit button depending on the conditions.
Try this
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
Try the below code -
var chk1 = document.getElementById('chk1');
chk1.addEventListener('click', checked, false);
var chk2 = document.getElementById('chk2');
chk2.addEventListener('click', checked, false);
function checked(){
if(chk1.checked && chk2.checked) {
document.getElementById('btn').removeAttribute('disabled');
} else {
document.getElementById('btn').setAttribute('disabled','disabled');
}
}
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<button id="btn" disabled >Button<button>
I tested it and it's working! Hope it helps u...

Use same function on multiple elements

I need this function to work on multiple elements in the form, right now it only works on TfDiagnosis.
How do I use it on TfDiagnosis and TfDiagnosis2 with results in TfSnowmed and TfSnowmed2?
JQUERY
$(function snowmedlist() {
$('#TfDiagnosis').on('click keyup change blur', function() {
if ($('#TfDiagnosis').val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($('#TfDiagnosis').val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
});
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2"></td>
It's easy to work on groups of elements using class names.
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="diagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
js:
$('.diagnosis').on('click keyup change blur', function() {
if($(this).val() == "...") {
$(this).next().val(1.00);
}
})
This way .next() is always the next element, so you don't need to keep passing IDs around. You can then store the data outside of the function to get rid of a cluster of IF statements:
var myData = []
myData['[D]Anterograde amnesia (780.93)'] = '206789002';
myData['[D]Chills with fever (780.60)'] = '206760004';
...then substitute the look-up from the array....
$('.diagnosis').on('click keyup change blur', function() {
$(this).next().val(myData[$(this).attr(id)]);
})
You can use
$('#TfDiagnosis, #TfDiagnosis2').on('click keyup change blur', function() {
if($(this).attr('id') == 'TfDiagnosis' ){
if ($(this).val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($(this).val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
}else{
//Stuff to do in case it is the #TfDiagnosis2
}
});
The most efficient way to make your function work on multiple inputs is to use event delegation:
$(document).on('click keyup change blur', 'input', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
Which will call the function for any input on the page. You probably want to assign a class to the specific inputs you want to use like so:
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="TfInput" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed" class="TfInput">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" class="TfInput" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2" class="TfInput">
JavaScript
$(document).on('click keyup change blur', '.TfInput', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});

Categories

Resources