jquery mobile populate select box from another but clear selection first - ajax

I have two select boxes and second gets updated with GET ajax on first select box selection.
It works cool, but...
If a person made a selection in the fist field (c) it updates field (s) correctly.
When a person made a selection in field (s) but then decide to select another option in (c), field (s) gets updated, but the previous selection of (s) do not clear, even that when it actually does update the options of (s)
What is missing in my code to clear the (s) field when new options are loaded?
<form data-parsley-validate method="post" action="#post1" data-ajax="false" data-theme="<?=$theme?>">
<div class="ui-field-contain ui-body ui-br">
<label for="c">Select Category:</label>
<select name="c" id="c" data-mini="true" placeholder="Select Category" required>
<option value="">Select Category</option>
<?
$ssql="SELECT * FROM cat";
$sresult=mysql_query($ssql);
while($srows = mysql_fetch_array($sresult)){
$cat_id = $srows['id'];
$cat_name = $srows['name'];
echo '<option value="'.$cat_id.'">'.$cat_name.'</option>';
}
?>
</select>
<script>
$(document).ready(function() {
$("#c").selectmenu(); // Initializes
$("#c").selectmenu('refresh', true);
$("#c").change(function() {
$("#s").load("getsub.php?c="+ $("#c").val());
$("#s").selectmenu('refresh', true);
});
})
</script>
</div>
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label for="s">Select Subcategory:</label>
<select name="s" id="s" data-mini="true" placeholder="Select Subcategory" required>
<option value="">Select Subcategory</option>
</select>
</div>
<input type="submit" value="Send" name="submit" data-theme="butt">
</form>

First off, you should not be using .ready() in jQuery Mobile, instead use "Page Events" to add listeners.
To clear selection of an existing selectmenu, you should mark first option as selected and then refresh it.
$(document).on("pagecreate", "#pageID", function () {
$("#c").selectmenu("refresh");
$("#c").on("change", function () {
$("#s").load("getsub.php?c="+ $("#c").val(), function () {
$("#s option:eq(0)").prop("selected", true); /* select first option */
$("#s").selectmenu("refresh"); /* refresh */
});
});
});

Related

Select2 clone is working only twice

I'm trying to clone a select2 list and 2 text areas, but it's working only for the first clone, and I don't understand why..any new eye will certainly help !
(the cloning is OK, but the select2 is not applied to the 3rd clone)
HTML part
<fieldset>
<div id="test">
<div>
<label>Tool Name : </label>
<select class="toollist" name="FSR_tool_id[]" style="width: 350px" />
<option></option>
<option value="1" >bla 1</option>
</select>
<input type="Button" value="ADD ANOTHER TOOL" class="AddTool">
<label>Service Scope</label>
<textarea rows="5" style="width:99%" name="FSR_servicescope[]" class="validate[required]" />
</textarea>
</br>
<label>Service Description</label>
<textarea rows="10" style="width:99%" name="FSR_servicedesc[]" class="validate[required]" />
</textarea><hr>
</div>
</div>
<input type="hidden" value="0" id="countertool">
</fieldset>
JS part (I call jquery and select 2 before, of course)
$('#test .toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
$("input[type='button'].AddTool").live('click',
function() {
var index = $(this).closest('div').index();
if (index > 0) {
$(this).closest('div').remove();
} else {
$('#test .toollist').select2('destroy');
//we have to destroy the select2 before cloning
var $div = $(this).closest('div').clone(true);
$div.find('input.AddTool').val("DELETE THIS TOOL");
//to replace the button "add" by another "delete"
var $input = $div.find('input.exp');
var index = $('input#countertool').val();
var id = 'exp' + index;
index++;
$('input#countertool').val(index);
$input.attr('id', id).data('index', index);
$(this).closest('#test').append($div);
//then, we re-apply select2 to the lists
$('#test .toollist').select2({
placeholder: "Search your tool !",
allowClear: true
});
};
});
Any idea of my mistake ?
Thanks a lot in advance !
See this fiddle: http://jsfiddle.net/omugbdm1/3/ it's a bit of a mashup of code but should do the trick.
<div id="test">
<div id="tooltest0" class="tooltest0">
<label>Tool Name :</label>
<select class="toollist" name="FSR_tool_id[]" id="FSR_tool_id0" style="width: 350px" />
<option></option>
<option value="1">bla 1</option>
</select>
</div>
<div id="tool-placeholder"></div>
<div>
<input type="button" value="Add another" />
</div>
</div>
and
$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
$('input[type=button]').click(function () {
$('.toollist').select2("destroy");
var noOfDivs = $('.tooltest0').length;
var clonedDiv = $('.tooltest0').first().clone(true);
clonedDiv.insertBefore("#tool-placeholder");
clonedDiv.attr('id', 'tooltest' + noOfDivs);
$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
});

how to validate a form without displaying any error messages

I do not understand how I can validate a form with jquery validate to display the Submit button or not.
My javascript is as follows:
ko.bindingHandlers.jqValidate = {
init: function (element, valueAccessor, option) {
var element = element;
var validateOptions = {
ignore: [":hidden:not(required)"],
focusCleanup: true,
onsubmit: true
};
function displaySubmitButton() { // Remove/Add class to submit button
if ($('form').valid()) $('.toSave').show();
else $('.toSave').hide();
}
$('form').bind('onchange keyup onpaste', function (event, element) {
if ($('form').valid() === true && $(element).not('.resetForm')) $('.toSave').show();
else if ($(element).not('.resetForm')) $('.toSave').hide();
});
}
};
My form :
<ol class="MutColor13 mouseOver" data-bind="jqValidate: {}">
<li class="rightCol">
<strong>
<label for="iEmailReply"><asp:Literal runat="server" ID="lEmailReply" /></label>
</strong>
<input id="iEmailReply" name="EmailReply" type="text" tabindex="2"
class="MutColor13 email"
data-bind="value: communication.Message.ReplyEmail, valueUpdate: 'afterkeydown'"
required="required" />
</li>
<li class="leftCol">
<strong>
<label for="iEmailFrom"><asp:Literal runat="server" ID="lEmailFrom" /></label>
</strong>
<input id="iEmailFrom" name="EmailFrom" type="text" tabindex="1"
class="MutColor13 email"
data-bind="value: communication.Message.SenderEmail, valueUpdate: 'afterkeydown'"
required="required" />
</li>
<!-- and more form input -->
</ol>
My submit button :
<div class="buttonBlock rightButton" data-bind="fadeVisible: validateMessage()">
<a class="MutButton3 toSave" data-bind="click: saveMessage"><span class="MutButton3">submit</span></a>
</div>
when I type "$ ('form'). valid ()" in the firebug console, all error messages appear. I do not think the submit button is the problem because I have not clicked at this point
How do I enable the display of the error message from the input short change while allowing the display of the submit button if fields (and any other form fields in the page) if all fields are valid?
I was inspired by this question: jquery validate: IF form valid then show submit button
a working demo : http://jquery.bassistance.de/validate/demo/
but the button is displayed continuously
ok I think this could work:
http://jsfiddle.net/Ay972/10/
what I did :
$('form').bind('change oninput', function (event, element) {
console.log('formLive :: ', $(event));
if ($('form').valid() === true && $(element).not('.resetForm')) $('.toSave').show();
else if ($(element).not('.resetForm')) $('.toSave').hide();
});
the 'change oninput' seems to work.

ASP MVC3 checkbox action without submit button

I am using ASP.net for a program with a number of check boxes and a submit button which initiates an action depending on the selected check boxes.
However, one of my check boxes should behave as this submit button, i.e, upon selecting/deselecting this check box, the same action as the button must be triggered. Can someone please help me in doing this (or perhaps direct me to a tutorial)
I have a controller class and model.
Thanks you
EDIT
The program look like:
#using(Html.BeginForm("controllername", FormMethod.Get)) {
#html.CheckBox("check1");
#HTMl.Checkbos("check2");
<input type="submit" value="Submit" />
}
Everything else is pretty much handled in the controller.
You can use javascript to listen to the check event of your check box and then invoke the form submit.
Assuming your markup of view is like this
<form id="yourFormId" action="user/post">
<input type="checkbox" class="optionChk" value="1" /> One
<input type="checkbox" class="optionChk" value="2" /> Two
<input type="checkbox" class="optionChk" value="3" /> Three
</form>
<script type="text/javascript">
$(function(){
$(".optionChk").click(function(){
var item=$(this);
if(item.val()=="2") //check your condition here
{
item.closest("form").submit();
}
});
});
</script>
EDIT : As per the question edit.
Change the CheckBox Helper method usage like the below to add a css class to the checkbox so that we can use that for the jQuery selection.
#Html.CheckBox("check1",new { #class="optionChk"})
imagining you have something like this:
#using(Html.BeginForm()) {
<label class="checkbox">
<input type="checkbox" name="chb_a" id="chb_a"> Option A
</label>
<label class="checkbox">
<input type="checkbox" name="chb_b" id="chb_b"> Option B
</label>
<label class="checkbox">
<input type="checkbox" name="chb_c" id="chb_c"> Option C
</label>
<label class="checkbox">
<input type="checkbox" name="chb_d" id="chb_d"> Option D
</label>
<button type="submit" class="btn">Submit</button>
}
you can write a simple jQuery to complement:
$(".submit").click(function() {
// find the <form> the element belongs and submit it
$(this).closest('form').submit();
});
and with this, all you need is to add a class named submit to any checkbox or more buttons if you want them to submit
for example:
<label class="checkbox">
<input type="checkbox" name="chb_e" id="chb_e" class="submit"> Option E
</label>
You can bind the click events on the checkboxes.
$( '.myCheckboxes' ).click(function () {
var clickedBox = $( this );
// now do something based on the clicked box...
});
If you need to know which checkboxes are checked, that's just another selector.
$( '.myCheckboxes:checked' ).each(function () {
// Now you have access to each checked box.
// Maybe you want to grab their values.
});
Just bind the checkbox to a click event. Assuming you have a way of uniquely identifying the checkbox that submits the form.
$( '#formSubmitCheckbox' ).click(function() {
$( '#myForm' ).submit();
});

input fields not showing in hide/show div with radio buttons

I have a very basic hide/show div function set up for when people click a certain radio button. In one of the hidden divs I need to create a form however when I add input fields to the hidden div my function stops working.
<div id="tabs">
<div id="nav">
<input type="radio" name="primary_contact_director" value="Yes" class="div1">Yes</input>
<input type="radio" name="primary_contact_director" value="No" class="div2">No</input>
</div>
<div id="div1" class="tab">
<p>this is div 1</p>
</div>
<div id="div2" class="tab">
<p>this is div 2</p>
</div>
</div>
<script type="text/javascript" charset="utf-8">
(function(){
var tabs =document.getElementById('tabs');
var nav = tabs.getElementsByTagName('input');
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<=nav.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
}
}
}
/*
* Show the clicked tab
*/
function showTab(tab){
document.getElementById(tab).className = 'tab'
}
hideTabs(); /* hide tabs on load */
/*
* Add click events
*/
for(var i=0;i<nav.length;i++){
nav[i].onclick = function(){
hideTabs();
showTab(this.className);
}
}
})();
This code works however when I add
<label class="title">First Name:</label>
<input type="text" name="first_name" class="form">
<label class="title">Last Name:</label>
<input type="text" name="last_name" class="form">
<label class="title">Business Address:</label>
<span class="instructions">Please enter a physical address. P.O. Boxes are not acceptable for filing.<br>
If your business is run out of your home, please list that address.</span><br>
<input type="text" name="business_address" class="form">
<label class="title">City:</label>
<input type="text" name="business_city" class="form">
<label class="title">State</label>
<select name="business_state">
<option value="California">California</option>
</select>
<label class="title">Zip Code:</label>
<input type="text" name="business_zip" class="form">
<label class="title">Business Phone Number:</label>
<input type="text" name="business_phone" class="form"><br>
to my div2 it stops working.
Hopefully this is a clear explanation. Any help is always appreciated!
In your hideTabs() function, you've got two typos.
First, you're iterating through the tab[] array, but you're checking it against the length of the nav[] array. This works because you have the same number of elements in your first example, but that's just a coincidence. If you evaluate it against the tab[] array's length, it will work better. The other problem you have is that your for loop ends at greater-than-or-equal-to length. THe problem is that arrays start counting at zero, so if the length is 3, the items on the list are tab[0], tab[1], and tab[2]. your code was trying to set something for tab[3], which didn't exist.
Here's the working code:
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<tab.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
}
}
}
In the future, you should look into using the javascript console in Chrome (or any other browser) to check for errors if your scripts stop working—usually there's an error that that will give you hints as to what's happening.

display selected item from dropdown onchange function into html label through javascript , please help how to it

<form method="post">
<select name="users" id="users" onchange="showUser(this.value)" value="">
<option value="">Select a person:</option>
<option value="1" onchange="copy();">tcs</option>
<option value="2" onchange="copy();">wipro</option>
<option value="3" onchange="copy();">Hcl</option>
<option value="4" onchange="copy();">krystal kones</option>
</select>
</form>
I have this drop down i want that when the value is changed like tcs,wipro or hcl then that value should shown in html label
Try putting the onChange attribute in the select tag.
Example: http://jsfiddle.net/r6Fus/
HTML:
<div id="label"></div>
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="tcs" >tcs</option>
<option value="wipro" >wipro</option>
<option value="Hcl" >Hcl</option>
<option value="krystal kones" >krystal kones</option>
</select>
Javascript:
function copy() {
document.getElementById("label").innerHTML = document.getElementById("mySelect").value
}
Otherwise you could use jQuery.
First of all, the onchange event is for the select element, not the option elements. Those don't actually change. Also, you have two JavaScript functions. showUser() and copy(). But you describe only one piece of functionality. What do these two functions do?
As for showing the text in the label, here's one way to do it (using jQuery, because everybody does):
$(document).ready(function() {
$('#users').change(function() {
$('#myLabel').text($(this).val());
});
});
What this is basically doing is:
Wait until the DOM is loaded and ready.
Bind a function to the change event of the specified select element.
The function contains one line, which sets the text of the specified label to the value of the select.

Resources