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
});
});
Related
I would like to send my dynamically generated DIV items, but I do not understand how to do it
I create my div dynamically:
$("#clt_forf_ti").click(function(e){
e.preventDefault();
if(x < max_input){
x++;
var addDIV = $('<div id="clt_forf_div'+x+'" class="w-100 form-control" ><label for="clt_forf_num'+x+'">Ligne :</label> <input type="text" class="font-weight-bold border-top-0 border-right-0 border-left-0 mR-10" id="clt_forf_num'+x+'" autocomplete="off" style="width: 100px" > Forfait : <i id="clt_forf_forf_select'+x+'" style="display:none;"></i><input type="text" class="border-top-0 border-right-0 border-left-0" id="clt_forf_forf'+x+'" autocomplete="off" style="width: 180px"><i class="ti-calendar mL-20 mR-5"></i><input type="text" class="border-top-0 border-right-0 border-left-0" id="clt_forf_date_start'+x+'" name="datepicker" placeholder="Début" style="width: 80px"><i class="ti-calendar mL-20 mR-5"></i><input type="text" class="border-top-0 border-right-0 border-left-0" id="clt_forf_date_end'+x+'" name="datepicker" placeholder="Fin" style="width: 80px"><i id="clt_forf_ti_remove" class="ti-close c-red-500 mL-5" style="cursor: pointer;"></i></div>');
$('#clt_forf_bloc').append(addDIV);
$('#clt_forf_forf'+x, addDIV).autocomplete(autocomp_opt);
$("input[id^='clt_forf_date']", addDIV).datepicker(datepick);
//$('#clt_forf_date_end'+x, addDIV).datepicker(datepick);
}
});
I want to send each value by ajax:
var data = {
op_clt_forf_ref: $("[id^='clt_forf_forf_select']").html(),
op_clt_forf_num: $("[id^='clt_forf_num']").val(),
op_clt_forf_start: $("[id^='clt_forf_date_start']").val(),
op_clt_forf_end: $("[id^='clt_forf_date_end']").val(),
op_clt_forf_nom: $("[id^='clt_forf_forf']").val(),
};
however he only takes me the first div and not the others,
can you help me ?
The Elements that you have created were not present in the DOM earlier. So can't target them directly.
Try doing this:
var data = {
op_clt_forf_ref: $('body #clt_forf_forf_select').html(),
op_clt_forf_num: $('body #clt_forf_num').val(),
op_clt_forf_start: $('body #clt_forf_date_start').val(),
op_clt_forf_end: $('body #clt_forf_date_end').val(),
op_clt_forf_nom: $('body #clt_forf_forf').val(),
};
I'm having trouble using the datasource the right way.
My Goal: create external widget for filtering kendo grid (server side filter).
I managed to make it work, but it's kind of a workaround and I am looking for the corrent approach
The filterGrid function do all the work but it doesn't look right,
I want the parametermap function to do all the work but I can't figure it out.
Please advise.
this is how my view model looks like (I omitted the less important parts):
var viewModel = kendo.observable({
selectedInterface: null,
selectedStatus: null,
toHilanDate: new Date(),
updateDate: new Date(),
employeeId: null,
factoryId: null,
eventId:null,
employees: new kendo.data.DataSource({
transport: {
parameterMap: function (data, type) {
return { criteria: data };//for the mvc controller
},
read: {
url: "tohilan/Employees",
type: "post",
data: {}
}
}
}),
filterGrid: function () {
var data = {
SelectedInterface: this.selectedInterface ? this.selectedInterface.Id:null,
SelectedStatus: this.selectedStatus? this.selectedStatus.Key:null,
ToHilanDate: kendo.toString(kendo.parseDate(this.toHilanDate), "d"),
UpdateDate: kendo.toString(kendo.parseDate(this.updateDate), "d"),
EmployeeId: this.get("employeeId"),
FactoryId: this.get("factoryId"),
EventId: this.eventId,
};
//set new data into datasource
$('#employeeGrid').data('kendoGrid').dataSource.transport.options.read.data = data;
//refresh grid
$('#employeeGrid').data('kendoGrid').dataSource.read();
$('#employeeGrid').data('kendoGrid').refresh();
}
});
kendo.bind($("#employees-view"), viewModel);
My markup looks like this: (again, only the important part)
<ul>
<li>
<label for="employeeId">מספר עובד:</label>
<input type="number" id="employeeId" data-role="maskedtextbox" data-bind="value:employeeId"/>
</li>
<li>
<label for="eventId">מספר אירוע:</label>
<input type="number" id="eventId" data-role="maskedtextbox" data-bind="value:eventId"/>
</li>
<li>
<label for="factoryId">מספר מפעל:</label>
<input type="number" id="factoryId" data-role="maskedtextbox" data-bind="value:factoryId"/>
</li>
<li>
<label for="toHilanDate">תאריך העברה לחילן:</label>
<input type="date" id="toHilanDate" data-role="datepicker" data-bind="value:toHilanDate" />
</li>
<li>
<label for="updateDate">תאריך עדכון:</label>
<input type="date" id="updateDate" data-role="datepicker" data-bind="value:updateDate" />
</li>
<li>
<label for="event-status">סטטוס אירוע:</label>
<select id="event-status" data-role="dropdownlist" data-bind="value: selectedStatus, source: statusList" data-text-field="Value" data-value-field="Key" data-option-label=" "></select>
</li>
<li>
<label for="interface">ממשק:</label>
<select id="interface" data-role="dropdownlist" data-bind="value: selectedInterface, source: interfaceList" data-text-field="Description" data-value-field="Id" data-option-label=" "></select>
</li>
<li>
<button type="submit" data-role="button" data-bind="events: {click:filterGrid}">סנן</button>
</li>
</ul>
I guess I found an answer, maybe I had a typo or something.
I created the data object in the parametermap function instead of the filterGrid function. I just replaced "this" with viewModel. I still think that there is even better way to deal with it but at the moment it serve me just right.
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 */
});
});
});
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.
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.