Ok guys here's the fiddle
http://jsfiddle.net/wKbXx/24/
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
} else {
$('option[value=' + this.value + ']').remove();
}
});
});
What I need to do is to select two colors with the check boxes. Let say red, and blue. Then using the select, Mark one red and one blue. Then check green. I want it to keep the selected data. Right now once you select green it wipes that data. How can I do that?
UPDATED TO REFLECT WORKING ANSWER.. UPDATED FIDDLE TOO
I would go for a slightly different approach; instead of always resetting the select boxes, I would check whether the text in the changed checkbox is already contained in the select boxes. If it is, I would assume it's been unchecked and remove the option from the select boxes. Otherwise I would append just that new option to the select boxes.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if (sel.find('option').text().indexOf(this.id) > 0) {
$('option[value=' + this.value + ']').remove();
} else {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
});
});
The downside with this version is that the order of the colors in the select boxes is determined by the order in which the checkboxes are clicked; with your version, the order of the colors in the select boxes is always the same as in the checkboxes.
(Hope that made sense.)
Here's a fiddle: http://jsfiddle.net/Niffler/0hLxzvh8/
This may be the answer to your question...
You should have your rewrite on top as well.
$(function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]' ).on( 'change', function() {
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
else {
//Remove where ID matches up
sel.children().remove();
}
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
});
});
Cheers!
You need to get the value of the select box before you replace the options, then reset the value at the end.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.each(function(){
sel.data('previous', sel.val());
});
// overwrite the existing options
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]:checked' ).each( function() {
sel.append( $("<option />").val(this.value).text( this.id ) );
});
// if it had a value, set it back to that.
if ( currentValue != '' ){
sel.each(function(){
sel.val(sel.data('previous'));
});
} else {
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
}
});
});
Related
I have a data table having 15 columns. Am using a below filter script which showing all the values in the combo box. It showing combobox filter for all the columns. but actually I don't need it. I want it for 2,4,5,6,12 Columns.I am using DataTables 1.10.16.
$("#dTable tfoot th").each( function ( i ) {
if ($(this).text() !== '') {
var isStatusColumn = (($(this).text() == 'Status') ? true : false);
var select = $('<select><option value=""></option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var val = $(this).val();
table.column( i )
.search( val ? '^'+$(this).val()+'$' : val, true, false )
.draw();
} );
if (isStatusColumn) {
var statusItems = [];
table.column( i ).nodes().to$().each( function(d, j){
var thisStatus = $(j).attr("data-filter");
if($.inArray(thisStatus, statusItems) === -1) statusItems.push(thisStatus);
} );
statusItems.sort();
$.each( statusItems, function(i, item){
select.append( '<option value="'+item+'">'+item+'</option>' );
});
}
else {
table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
}
```
[![Actuall View of the table now][1]][1]
[![I want like this][2]][2]
[1]: https://i.stack.imgur.com/gVZiR.png
[2]: https://i.stack.imgur.com/fqGWI.png
You could add a dynamic class to each select, then just display:none with CSS.
var select = $('<select class="' + i + '"><option value=""></option></select>')
then...
.variableName1,
.variableName5,
.variableName6,
.variableName7,
.variableName8,
.variableName9 {
display:none;
}
Currently I have a combobox which options gets echo'd by PHP since the values are in an array. The code of the combobox is as follows:
<div class="ui-widget">
Project
<br>
<select id="combobox">
<?php
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
?>
</select>
</div>
What I am trying to achieve is when a user types into the combobox he gets a dropdown-list with all the entries of the array that match the text the user typed in the combobox.
The user can then select an option from the dropdown-list or choose to type the entry completely(but it needs to mach the entries in the dropdown-list).
To achieve all this i am currently using the Autocomplete function of jQuery.
All the code that I am using to achieve this can be watched here: http://jqueryui.com/autocomplete/#combobox.
The code for the combobox I use is as follows:
<script>
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
});
</script>
The problem that I am having right now is when a user types text in the combobox and the dropdown-list appears and he fully types out an entry of the dropdown-list the combobox still gets cleared. This is not supposed to happen. Whenever the user clicks on the combobox the item doesn't get cleared.
To make is a bit clearer here is an image of the combobox:
So above you can see the combobox. Whenever a user types something he gets a dropdown-list with all the results matched(project 1, project 10).
The problem that I am having right now is when a user types out "project 1" without clicking on the item in the dropdown-list the text in the combobox still gets removed by the Autocomplete function in jQuery.
If the user clicks on the item then there is no problem at all.
Funny thing is that the Autocomplete function works without any problems if I don't echo the option elements with PHP.
so:
<option value="project 1">project 1</option>
<option value="project 2">project 2</option>
<option value="project 3">project 3</option>
instead of:
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
Any help is greatly appreciated.
Change from
echo "<option value=".$value.">".$value."</option>";
TO
echo "<option value='".$value."'>".$value."</option>";
Thanks to Stryner for his code How to disable a search/filter on a specific column on a datatable?
which is exactly what I was looking for.
BUT, if bottom TH cells do display the inputs where needed, on blur/change/keyup, nothing happends...
Console : Undefined is not a function
- corresponding to " oTable.columns().eq( 0 ).each( function ( colIdx ) {"
Can you help me to solve this, please ?
Thank u :))
$('#datos tfoot th').not(":eq(0),:eq(3),:eq(5),:eq(6)") //Exclude columns 0, 3, 5 and 6
.each( function ()
{
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Rechercher" />' );
});
var oTable = $('#datos').dataTable();
oTable.columns().eq( 0 ).each( function ( colIdx ) {
if (colIdx == 0 || colIdx == 3 || colIdx == 5 || colIdx == 6) return; //Do not add event handlers for these columns
$( 'input', table.column( colIdx ).footer() ).on( 'keyup blur change', function () { oTable
.column( colIdx )
.search( this.value )
.draw();
});
});
My server-side script is the same as this one at the bottom of the page daniweb.com/web-development/php/threads/467455/convert-datatables-to-server-side-processing
Thanks
Please try this for your keyup event and let me know if it works. I've used this long time ago so can't be sure if it works for you, but maybe it helps:
$("tfoot input").keyup( function () {
/* Filter on the column (the index) of this element */
oTable.fnFilter( this.value, $("tfoot input").index(this) );
} );
I'm using the ScrewDefaultButtons jQuery plugin to replace checkboxes w/ images. The plugin uses the following code to successfully hide the checkbox and replace it with a checked/unchecked image:
$('input:checkbox').screwDefaultButtons({
image: "url(../../images/radio_check.png)",
width: 14,
height: 14
});
The issue I'm experiencing arises when trying to combine these custom checkboxes with a To-Do List plugin that uses a checkbox to mark items as completed. When an item is complete, the checkbox is ticked and the item gets moved to a "completed items" list via PHP and AJAX.
The above code successfully replaces the default checkbox w/ the custom image, but when the new checkbox is ticked, nothing occurs except the "unchecked" image changes to a "checked" image. With the default checkbox, an alert pops up confirming whether you want to move the item or not, and if confirmed, the item is moved.
The big question is: How do I get the ScrewDefaultButtons checkbox to work w/ my To-Do List's checkbox function?
This is the code for the checkbox:
Output of the default checkbox:
<td id="checkbox_parent">
<input id="ctdl-1852" class="todo-checkbox uncompleted" type="checkbox"></input>
<input type="hidden" value="a193d8dc3a" name="cleverness_todo_complete_nonce"></input>
</td>
Output of the ScrewDefaultButton checkbox:
<td id="checkbox_parent">
<div class="todo-checkbox uncompleted styledCheckbox" style="background-image: url("../../images/radio_check.png"); width: 14px; height: 14px"> … </div>
<input type="hidden" value="a193d8dc3a" name="cleverness_todo_complete_nonce"></input>
</td>
PHP:
protected function show_checkbox( $id, $completed = NULL, $layout = 'table', $single = '' ) {
$permission = CTDL_Lib::check_permission( 'todo', 'complete' );
if ( $permission === true ) {
if ( is_admin() || $layout == 'table' ) $this->list .= '<td id="checkbox_parent">';
if ( $completed == 1 ) {
$this->list .= sprintf( '<input type="checkbox" id="ctdl-%d" class="todo-checkbox completed'.$single.'" checked="checked" />', esc_attr( $id ) );
} else {
$this->list .= sprintf( '<input type="checkbox" id="ctdl-%d" class="todo-checkbox uncompleted'.$single.'" />', esc_attr( $id ) );
}
$cleverness_todo_complete_nonce = wp_create_nonce( 'todocomplete' );
$this->list .= '<input type="hidden" name="cleverness_todo_complete_nonce" value="'.esc_attr( $cleverness_todo_complete_nonce ).'" />';
if ( is_admin() || $layout == 'table' ) $this->list .= '</td>';
}
}
jQuery: (Note: adding .bind("click", function () { does not fix the issue)
$( '.todo-checkbox' ).click( function () {
var confirmed = confirm( ctdl.CONFIRMATION_CHECK );
if ( confirmed == false ) return false;
var status = 1;
var id = $( this ).attr( 'id' ).substr( 5 );
var todoid = '#todo-' + id;
var single = $ ( this ).hasClass( 'single' );
if ($( this ).prop( 'checked' ) == false ) status = 0;
var data = {
action: 'cleverness_todo_complete',
cleverness_id: id,
cleverness_status: status,
_ajax_nonce: ctdl.NONCE
};
jQuery.post( ctdl.AJAX_URL, data, function( response ) {
if ( single != true ) {
$( todoid ).fadeOut( function () {
$( this ).remove();
});
$( '.todo-checkbox' ).prop( "checked", false );
}
} );
} );
EDIT (07/28/13): Output with Hauke's first code:
<td id="checkbox_parent">
<div class="todo-checkbox uncompleted styledCheckbox" style="background-image: url("../../images/radio_check.png"); width: 14px; height: 14px; cursor: pointer; background-position: 0px 0px;"> … </div>
<input type="hidden" value="a81d045af8" name="cleverness_todo_complete_nonce"></input>
</td>
When the checkbox is clicked, the only difference in the output is the height of the background-position changes to -14px.
ScrewDefaultButtons creates a wrapper HTML element around the actual input element. Therefore, you can't rely on this being the neccessary input element when using it inside the click event handler. Instead, you'll have to find the input element first. You can accomplish this by doing something like this:
var inputElement;
if( $( this ).is( 'input' ) )
inputElement = $( this );
else
inputElement = $( this ).children().first();
With the inputElement found, you can get its id etc. then:
var id = inputElement.attr( 'id' ).substr( 5 );
var todoid = '#todo-' + id;
var single = inputElement.hasClass( 'single' );
if (inputElement.prop( 'checked' ) == false ) status = 0;
To test this, I created a small jsFiddle here: http://jsfiddle.net/Q8s96/3/
EDIT: In the jsFiddle I did not deal with this line:
$( '.todo-checkbox' ).prop( "checked", false );
You'll have to replace it with something that first detects if ScrewDefaultButtons was applied to the checkbox. If it was applied, you'll have to change the checked property of its first child. If it was not applied, you can directly change the checked property.
Something like this:
$( '.todo-checkbox' ).each( function () {
if( $( this ).is( "input" ) )
$( this ).prop( "checked", false );
else
$( this ).children().first().prop( "checked", false );
});
Try replacing $( '.todo-checkbox' ).click( function () { with $(document).on("click", '.todo-checkbox', function { (assuming you have jQuery 1.7+):
$(document).on('click', '.todo-checkbox', function {
var confirmed = confirm( ctdl.CONFIRMATION_CHECK );
if ( confirmed == false ) return false;
var status = 1;
var id = $( this ).attr( 'id' ).substr( 5 );
var todoid = '#todo-' + id;
var single = $ ( this ).hasClass( 'single' );
if ($( this ).prop( 'checked' ) == false ) status = 0;
var data = {
action: 'cleverness_todo_complete',
cleverness_id: id,
cleverness_status: status,
_ajax_nonce: ctdl.NONCE
};
jQuery.post( ctdl.AJAX_URL, data, function( response ) {
if ( single != true ) {
$( todoid ).fadeOut( function () {
$( this ).remove();
});
$( '.todo-checkbox' ).prop( "checked", false );
}
} );
} );
perhaps it is duplicate,but i can't found solution so i posted this question.I am use jquery ui for auto complete search box. it works fine but the problem is i want to search using id.example:when user type paris,i try to send city_id in mysql for search. so problem is how to pass hidden id with json?
here the code:
<input type="text" name="grno" id="grno" class="input" title="<?php echo $lng['vldgrno'];?>
jquery code:
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#grno" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "pages/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
alert(data.id);
return false;
}
});
});
</script>
autocomplete.php :
<?php
mysql_connect('localhost','root','');
mysql_select_db('school');
$return_arr = array();
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
//create select query
$query = "select `grno`,`first_name`,`student_id` from `tbl_student` where `grno` like '%".$term."%' or `first_name` like '%".$term."%'";
// Run the query
$result = mysql_query ($query);
$array = array();
while($obj = mysql_fetch_array($result)){
$array['name'] = $obj['first_name']."(".$obj['grno'].")";
array_push($return_arr,$obj['first_name']."(".$obj['grno'].")");
}
$json = json_encode($return_arr);
echo $json;
?>
so.how to pass student_id in autocomplete.php,like label and value.{label='xyz' value='1'}
In autocomplete.php replace this code
array_push($return_arr,array("value"=>$obj['student_id'],"label"=>$obj['first_name']."(".$obj['grno'].")"));
and in your script change this
terms.push( ui.item.label );
$( "#stud_id" ).val( ui.item.value );
hope,this is what you find.