If radio button is selected show alert - javascript

I want an alert to show when i click a radio button.
My radio buttons:
<div class="genericFormField">
New:#Html.RadioButtonFor(m => m.Form.InstallType, 1, Model.InstallationHeader.InstallType == 1 ? new { Checked = "checked" } : null )
Pool:#Html.RadioButtonFor(m => m.Form.InstallType, 2, Model.InstallationHeader.InstallType == 2 ? new { Checked = "checked" } : null)
Refurb:#Html.RadioButtonFor(m => m.Form.InstallType, 3, Model.InstallationHeader.InstallType == 3 ? new { Checked = "checked" } : null)
</div>
So if the radio button new is selected i want an alert to say "NEW" otherwise nothing.
Normally it is easy because you have id but in this occasion there is no ID?
As this is RadioButtonFor.
Thanks
New code
Full code:
$('input[name="Form.InstallType"]').on('change', function() {
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === '1') {
var validOptions = "#Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val();
previousValue = "";
$('#abc').autocomplete({
autoFocus: true,
source: validOptions,
}).change(function(){
var source = validOptions;
var found = $('.ui-autocomplete li').text().search(source);
console.debug('found:' + found);
var val = $('input[name="Form.InstallType"]:checked').val();
if (found < 0 && val === '1') {
$(this).val('');
alert("Please choose from auto complete");
}
});
}
});
This works, however if the radio button is on page load it doesnt work, i have to click another radio button and then click "new" and then it will work..
any chance it works on if its checked already rather than when check.

#Html.RadioButtonFor creates a proper input with name and id attributes.
You can access the value this way:
$('input[name="Form.InstallType"]:checked').val();
Not sure about generated radios' name as it is an inner variable.
Render page and look at generated name. This is how it looks in my case.
Now, about your alert. You need to listen to change event.
$('input[name="Form.InstallType"]').on('change', function()
{
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === '1') alert('New');
});
Why '1'? Because you have set it in the ASP.NET code.
This is how it should look like.
<div class="genericFormField">
New: #Html.RadioButtonFor(m => m.Form.InstallType, 'new')
Pool: #Html.RadioButtonFor(m => m.Form.InstallType, 'pool')
Refurb: #Html.RadioButtonFor(m => m.Form.InstallType, 'refurb')
</div>
<script>
$(document).ready(function() {
AlertIfNewIsSelected(); // Check if it is selected on page load. According to the question in comments.
$('input[name="Form.InstallType"]').on('change', AlertIfNewIsSelected);
});
function AlertIfNewIsSelected()
{
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === 'new') alert('New');
}
</script>
Of course, it all can be reached without using jQuery.

Related

JavaScript in Zend and jQuery Mobile

I'm developing an application in ZF1, using jQuery Mobile. I have a form (fragment):
$options = array('Employee', 'Supervisor', 'Other');
$form1->addElement('select', 'role', array('multioptions' => $options);
$form1->role->setAttribs(array('onchange', 'showHide()'));
$form2->addElement('text', 'position');
I have a script:
function showHide(){
var hide = false;
if(document.getElementById("form1-role").value === "Employee" ||
document.getElementById("form1-role").value === "Supervisor") {
hide = false;
} else {
hide = true;
}
var i;
var elements = [
"form2-position-label",
"form2-position-element"
];
for(i = 0; i < elements.length; i++) {
if(document.getElementById(elements[i]) !== null) {
document.getElementById(elements[i]).hidden = hide;
}
}
}
The idea is - when user selects 'Other' from the list the Textbox 'position' suppose to hide. Otherwise it should be visible. Everything works fine until form validation returns false - then validator messages appear and script stops working.
What is interesting - when I put alert("hello"); to the script, it does show the alert but still doesn't hide the textbox.
You can remove your $form1->role->setAttribs(array('onchange', 'showHide()')); and use this (seeing as you have jQuery on the page anyway).
$(function(){
$('#form1-role').on('change', function(){
var role = $(this).val();
$('#form2-position-label, #form2-position-element')
.toggleClass('hidden', role !== 'Employee' && role !== 'Supervisor');
});
});
This toggles a class on the target elements. So the CSS is simple:
.hidden {
display: none;
}
If you want this to activate on the page rendering as well (i.e. if there is an error message to display), you can put .change(); at the end of the on call.
$(function(){
$('#form1-role').on('change', function(){
var role = $(this).val();
$('#form2-position-label, #form2-position-element')
.toggleClass('hidden', role !== 'Employee' && role !== 'Supervisor');
}).change();
});
This will trigger a change event as soon as the page renders and execute the logic within the handler.

On Checkbox click event, Unable to remove checked="checked' attribute

I have a Jquery Dialog box within my view, In this dialog box there is a UL LI list which is transformed to a treeview. I retain previous checkbox checked selection by adding the checked attribute in my HTML Text Writer helper. What I am trying to do is to remove the checked attribute once its un-checked. I am able to fire the event and get the value for instance true or false for check or uncheck but I am not able to scuccessfully remove the checked attribute if it was checked. The DOM still have the previous state of checked.
HTML Writer
InUl(() => locations.ForEach(location => InLi(() =>
{
var children = this.childrenRenderer(location);
bool childStatus = !(children != null && children.Count() > 0);
if (childStatus)
{
writer.AddAttribute("type", "checkbox");
writer.AddAttribute("value", urlRenderer(location));
writer.AddAttribute("id", htmlPrefix + urlRenderer(location));
writer.AddAttribute("onclick", "handleClick(this)");
if (keys != null)
{
if (keys.Contains(Convert.ToInt32(urlRenderer(location))))
{
writer.AddAttribute("checked", "checked");
}
}
writer.RenderBeginTag("input");
}
writer.Write(locationRenderer(location));
if (childStatus)
{
writer.RenderEndTag();
}
RenderLocations(children);
})));
JS Function
function handleClick(e) {
alert("Click, new value = " + e.checked);
var $this = $(this);
if (e.checked = false) {
$this.removeAttr('checked');
}
}
If I uncheck a checkbox, the following function still gives the old checkbox which is now unchecked:
$("#errorCodes input:checkbox:checked").each(function () {
var v = $(this).val();
a.push(v);
if (errorTextArea.length > 0) {
errorTextArea = errorTextArea + " | ";
}
errorTextArea = errorTextArea + v;
});
Try this:
function handleClick(e) {
alert("Click, new value = " + e.target.checked);
if (e.target.checked == false) {
e.target.removeAttr('checked');
}
}
You have a simple error in your code:
if (e.checked = false)
should read
if (e.checked == false)

Overriding page input field in pagingtoolbar with extjs 4.2

I need to detect changes on page change in page input field of pagingtoolbar in extjs 4.2.
I am going through docs, but can't find any method for it. I have successfully overridden next, previous, &c., buttons, but can't find anything to override page input field. How would you go about this?
I have added afterrender listener on ExtJS Combobox component. You can add accordingly to override input field of paging toolbar. Here is the working code :
'afterrender' : function(thisCombo){
thisCombo.getPicker().pagingToolbar.addListener('change', function() {
var me = this;
thisCombo.getPicker().pagingToolbar.child("#inputItem").addListener('specialkey', function(field, e) {
if (e.getKey() == e.ENTER) {
///// Do your modifications here
var inputItem = thisCombo.getPicker().pagingToolbar.child('#inputItem').getValue();
total = me.getPageData().pageCount;
if (inputItem <= total) {
if (me.fireEvent('beforechange', me, inputItem) !== false) {
me.store.inputItemPage({
// Enter params
});
}
}
}
});
});
}
}
this example my help
As in the code you can all of the texts given that they have setter etc
http://jsfiddle.net/acteon/sZ3y6/1/
Ext.toolbar.Paging.override({
onLoad: function () {
var me = this,
pageData, currPage, pageCount, afterText, count, isEmpty;
count = me.store.getCount();
isEmpty = count === 0;
if (!isEmpty) {
pageData = me.getPageData();
currPage = pageData.currentPage;
pageCount = pageData.pageCount;
afterText = Ext.String.format(me.afterPageText, (isNaN(pageCount) || (pageCount === 0)) ? 1 : pageCount);
} else {
currPage = 0;
pageCount = 0;
afterText = Ext.String.format(me.afterPageText, 1);
}
Ext.suspendLayouts();
me.child('#afterTextItem').setText("my precious text");
// this one is the input field
me.child('#inputItem').setDisabled(isEmpty).setValue(currPage);
me.child('#first').setDisabled(currPage === 1 || isEmpty);
me.child('#prev').setDisabled(currPage === 1 || isEmpty);
me.child('#next').setDisabled(currPage === pageCount || isEmpty);
me.child('#last').setDisabled(currPage === pageCount || isEmpty);
me.child('#refresh').enable();
me.updateInfo();
Ext.resumeLayouts(false);
if (me.rendered) {
me.fireEvent('change', me, pageData);
}
}
});
thanks for your help.
I have another issue, #inputItem field. What event handles the enter/return key? I need to override this function, because I have a disable/enable button.

Displaying a hidden text box when a particular option value selected

I am trying to make a hidden text-box visible when a particular option value is selected, It works when there are multiple options available obviously because it responds to onChange. How can I get it to work if that is the only option present, the first select box in my Example.
Js Fiddle - http://jsfiddle.net/8bm9R/
This is my Js function
function showOther(fieldObj, otherFieldID) {
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue == 'other') ? '' : 'hidden';
return;
}
I've updated the JsFiddle:
Basically JsFiddle is misused, the function should be set to be wrapped in the header instead of 'onLoad'.
jsfiddle.net/8bm9R/2/
function showOther(fieldObj, otherFieldID)
{
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}
Cheers
$("select").change(function() {
if($(this).val() == "expected_value") {
otherFieldObj.style.visibility = "visible"
}
else {
otherFieldObj.style.visibility = "hidden"
}
});

Javascript: How to make this function working for click effects

I am designing a page where it displays the staff details in following structure :
user can click anywhere in the details box and the checkbox will get selected along with the change in the className of the details <div> box.
The problem i m facing is when i click anywhere in the details box it works fine.. but when i click on checkbox it only changes the className but doesnt make any changes to checkbox.
Also there is one condition, few users are allowed to selected limited staff at a time and few are allowed to select all of them..
I have assigned a myClick() function to the outer <div> box (one with red border)
and the function is :
var selectedCount = 0;
myClick = function(myObj,event)
{
var trgt =(event.srcElement) ? event.srcElement : event.target;
tgName = trgt.tagName;
//following statement gives me correct details element event though i clicked on any child tags
theElem = (tgName == 'DIV') ? trgt : ( (tgName == 'B') ? trgt.parentNode.parentNode : trgt.parentNode);
if(allowed_selection == 'unlimited')
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
}
else if(theElem.className == 'details_hover')
{
theElem.className = 'details_clicked';
if(tgName != 'INPUT') theElem.getElementsByTagName('input')[0].checked = true;
}
}
else
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
selectedCount--;
}
else if(theElem.className == 'details_hover')
{
if(selectedCount == allowed_selection ) return false;
theElem.className = 'details_clicked';
//i think, this is the suspicious area for errors
theElem.getElementsByTagName('input')[0].checked = true;
selectedCount++;
}
}
return false;
};
The problem is these return lines in your function:
return false;
When you connect an event to a form element that performs an action, such as a checkbox or button, returning false will prevent that default action. It stops the event from taking place as it regularly would.
You could try something like this at the top of your function:
var returnValue = (tgName == 'INPUT' && trgt.type == "checkbox") ? true : false;
And then when calling 'return ', use:
return returnValue;
If you return true you allow the checkbox to act as normal and check / uncheck itself.

Categories