Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Wednesday, February 9, 2022

jQuery filter/search function in table




https://www.w3schools.com/bootstrap/bootstrap_filters.asp# 

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

 

Thursday, January 3, 2019

Move cursor at end after paste in jQuery




Using $(this).html(textstring1) in JavaScript,   the  cursor will be at the top.
The following code is to move cursor to the end:
        $.fn.focusEnd = function() {
            $(this).focus();
            var tmp = $('<span />').appendTo($(this)),
                node = tmp.get(0),
                range = null,
                sel = null;

            if (document.selection) {
                range = document.body.createTextRange();
                range.moveToElementText(node);
                range.select();
            } else if (window.getSelection) {
                range = document.createRange();
                range.selectNode(node);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            }
            tmp.remove();
            return this;
        }

Example:
function clickother_cflnew($td){
        $.fn.focusEnd = function() {
            $(this).focus();
            var tmp = $('<span />').appendTo($(this)),
                node = tmp.get(0),
                range = null,
                sel = null;

            if (document.selection) {
                range = document.body.createTextRange();
                range.moveToElementText(node);
                range.select();
            } else if (window.getSelection) {
                range = document.createRange();
                range.selectNode(node);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            }
            tmp.remove();
            return this;
        }
        $td.find('.cfl_new_other').on('paste', function(event){
                event.preventDefault();

                var text = (event.originalEvent || event).clipboardData.getData('text/plain') || prompt('Paste something..');

                window.document.execCommand('insertText', false, text);
                textstring = $(this).html();
                textstring1 = textstring.replace(/<div>/g, '<br>').replace(/<\/div>/g, '');
                textstring1 = textstring1.replace(/&nbsp/g, ' ');
                $(this).html(textstring1);
               // $(this).html($(this).html().replace(/<div>/g, '<br>').replace(/<\/div>/g, '<br>'));
                 $(this).focusEnd();


        });
   
        $td.find('.cfl_new_other').unbind('keyup change input').bind("keyup change input",function() {
                el = $(this);
                textstring = el.html();
                textstring1 = textstring.replace(/<div>/g, '<br>').replace(/<\/div>/g, '');
                textstring1 = textstring1.replace(/&nbsp/g, ' ');
                if(textstring1.length >= 500){
                    alert("Maximum 500 characters");
                    el.html( textstring1.substr(0, 500) );
                     el.focusEnd();
                     $(this).parent().find(".charNum").text( " 0 character remaining.");
                } else {
                    $(this).parent().find(".charNum").text((500-textstring1.length) + " characters remaining.");
                }
        });   
}       

Friday, November 23, 2018

JS/JQuery: paste the plain text only





When I copy the Word document to the text box,
in background a lot html codes and strange characters from Word
are saved.
Below is the JS/JQuery code to paste the plain text ( I have a text box with class comment):

function clickcomments($td){

    $td.find('.comment').on('paste', function(event){
            event.preventDefault();

            var text = (event.originalEvent || event).clipboardData.getData('text/plain') || prompt('Paste something..');

            window.document.execCommand('insertText', false, text);

            $(this).html($(this).html().replace(/<div>/g, '<br>').replace(/<\/div>/g, '<br>'));

    });
}        

Wednesday, November 21, 2018

Get the dropdown list value and list in JQuery





I have a dropdown list class TaList in a column in a table.
To get the option value of dropdown list in JQuery:
  row3.find('td.TaList select').val();
To get the selected text of dropdown list in JQuery:
  stakeholder_name1 = row3.find('td.TaList :selected').text();
More codes:
$('div.ajax_list').find("#defaultTable").find('tr').each(function() {
    if($(this).find('.swap_option').attr('checked') == 'checked') total += 1;
    var row3=  $(this);
    if(total==1 && $(this).find('.swap_option').attr('checked') == 'checked'){
        courses_offered_id1=row3.find("input.courses_offered_id").val();
        stakeholder_id1 = row3.find('td.TaList select').val();
        stakeholder_name1 = row3.find('td.TaList :selected').text();
        section1 = row3.find('.TutSection').html();
        assignedID1 = row3.find('.assignedID').val();
    }
    if(total==2 &&$(this).find('.swap_option').attr('checked') == 'checked'){
        courses_offered_id2=row3.find("input.courses_offered_id").val();
        stakeholder_id2 = row3.find('td.TaList select').val(); 
        assignedID2 = row3.find('.assignedID').val();
        stakeholder_name2 = row3.find('td.TaList :selected').text();
        section2 = row3.find('.TutSection').html();               
    }           
});  

Friday, December 25, 2015

jQuery wildcard class, or name selector





You may need to click only via select only a class or name containing a string.
 Jquery has wildcard class or name selector. For example

// handle elements like <div class="someclass1"></div>
$('[class^="someclass"]').click(function() {
   // do stuff
});

// handle elements like <div class="foo someclass1"></div>
$('[class*=" someclass"]').click(function() {
   // do stuff
});
 
Reference:
 http://stackoverflow.com/questions/3697542/is-there-a-wildcard-class-selector

Monday, August 31, 2015

jQuery, save old select value and restore in dropdown menu



Use  following in click function
  $(this).attr('oldValue',$(this).val());
to store old select value in dropdown menu
Restore later in change function
 var oldValue = $(this).attr('oldValue');
More code
   $('div.ajax_list  td.TaList select').live('click', function(){   
       $(this).attr('oldValue',$(this).val());
       });
    $('div.ajax_list  td.TaList select').live('change', function(){
        var row = $(this).parent().parent();
        var oldValue = $(this).attr('oldValue');
        var worksheet = $('select#viewWorksheet').val();

            var section = row.find('td.TutSection input').val();
            var ta = row.find('td.TaList select').val();
            var startTime = row.find('td.StartTime select.StartHour').val()+':'+row.find('td.StartTime select.StartMinute').val()+' '+row.find('td.StartTime select.StartPeriod').val();
            var endTime = row.find('td.EndTime select.EndHour').val()+':'+row.find('td.EndTime select.EndMinute').val()+' '+row.find('td.EndTime select.EndPeriod').val();
            var Day = row.find('td.Day select').val();
            var Room = row.find('td.Room input').val();
            var enrolMax = row.find('td.EnrolMax input').val();
            var tutorialID = row.find('td input.tutorialID').val();
            var course_id = row.find('td input.course_id').val();
            var courses_offered_id = row.find('td input.courses_offered_id').val();
            var status = row.find('td.Status select').val();
            var type = row.find('td.type').html();
            var assign_id =row.find('td input.assignedID').val();
            var assign_id0 = 0;   
            if (assign_id == '' || assign_id == null || assign_id==0) {
                  //  assign_id =0;
                  //  var d = new Date();
                  //  assign_id0 = d.valueOf();
                  //  row.find('td input.assignedID').val(assign_id0);
                   row.find('td input').prop('disabled', true);
            }

            $.post('../_ajaxParts/TA/SITAAssignment.php',
                {funct:'updateSITA',
                tutorialID:tutorialID,
                course_id:course_id,
                courses_offered_id:courses_offered_id,
                section:section,
                ta:ta,
                taprev:ta1,
                type:type,
                assign_id:assign_id,
                assign_id0:assign_id0,
                day:Day,
                startTime:startTime,
                endTime:endTime,
                room:Room,
                enrolMax:enrolMax,
                status:status}, function(data){
               
                     formatJson(data,"div#notice", function(json){
                       row.find('td input').prop('disabled', false);
                       if(json.data['NotAllowed']==1) {
                        alert('LTD not allowed for SI assignment');
                        row.find('td.TaList select').val(oldValue);
                       }else if(json.data['NotAllowed']==2) {
                        alert('Adjunct appoinment not allowed for SI assignment');
                        row.find('td.TaList select').val(oldValue);
                       }else if(json.data['NotAllowed']==3) {
                        alert('The assignment is not allowed due to related contract blocked.');
                        row.find('td.TaList select').val(oldValue);

                       }                      
                       else {
                       if (json.data['lastid'] != '' && json.data['lastid'] != null && json.data['lastid']!=0  &&json.data['status']=='Insert')  
                       row.find('td input.assignedID').val(json.data['lastid']);
                            if(json.data['success']==1)
                                formatJson('{"success":"SI\/TA Info Updated."}', "div#notice", null);
                            else
                                formatJson(json.data, "div#notice", null);
                     }           
               });   
            });
   

    });

Wednesday, July 1, 2015

jQuery, toggle the display





To change display none
 row.find("td input.memo").css("display","none");
to display 
 row.find("td input.memo").css("display","block");
But this may case alignment distorted, it id better to use toggle
   row.find("td input.memo").toggle();

Saturday, May 23, 2015

Trigger a click in jQuery




To trigger a click in jQuery, for example id stakeholderAccesses:
   $('#stakeholderAccesses').click();
 I found following trigger function not working well:
 $('#stakeholderAccesses').trigger('click');
Complete example:
$(document).ready(function() {

        //Display and Load the body part when the header is clicked.

        $('#stakeholderAccesses').click(function() {
                if( $(this).parent().children('div').css("display") == "none" ) {
                        $(this).html( '-' + $(this).html().substring(1) );
                        $(this).parent().children('div').load('../_ajaxParts/CVS/CVS_Access.php', {sid: $.url.param('sid')}).show('fast');
                }
                else {
                        $(this).html( '+' + $(this).html().substring(1) );
                        $(this).parent().children('div').hide('fast');
                }
        }).hover(function() {$(this).css('cursor','pointer');},function() {$(this).css('cursor','auto');});

         $('#stakeholderAccesses').click();
});

Sunday, February 15, 2015

jQuery prepend and append method






The prepend() method inserts specified content at the beginning of the selected elements
and append method  is to insert content at the end of the selected elements.
Example
               $blockAll = $(" <input type='button' class='block all' value='Block All Salary \> 0' />");
                $("div.ajax_list").prepend($blockAll);

                $viewAllPdf = $("<input type='button' class='viewallpdf' value='Preview All Contracts with Salary \> 0 (May take up to 5 minutes)' />");
            $("div.ajax_list").prepend($viewAllPdf);


The button  viewallpdf will come first and blockall button comes after.

Thursday, December 18, 2014

jQuery, combine different functions together




For example I have input button
<input type='button' class='previewButton' value='preview' />
I have general function for input method
    $resultTable.find('input').change(function() {
}
But change is not applied to button, as button reacts to click. To call change function for button:
   $resultTable.find('input.previewButton').click(function(event) {
              $(this).change();

}

Thursday, December 11, 2014

jQuery, selct and click radio button



For radio buttons in HTML
     <input type="radio" name="test" id="test1" />test1<br/>
     <input type="radio" name="test" id="test2" />test2<br/>
     <input type="radio" name="test" id="test3" />test3</br>
To get selected value:
$('input:radio[name=test]:checked').val();
 
To perform an action when click the radio button

$(function(){

$('input:radio[name=test]').change(
    function(){
        alert('changed');   
    }
);          

});
To set the first button checked:
$('input:radio[name=test]:nth(0)').attr('checked',true);
or
$('input:radio[name=test]')[0].checked = true;

Thursday, November 20, 2014

jQuery - sum over columns in a table or over input box




I have a table, there  is an input box in a column, beside there is default value near input box.
There are also default values inside input box. I want to add a summary row to show total.
When the input value is changed, the total row also needs to reflect the change.
below is the code:
$(document).ready(function() {
        var $resultTable = $("<table class='list'></table>");
        var $header = $("<tr><th>#</th><th>Saving</th>");
         $resultTable.html($header);
         for(var i = 0; i< 10; i++){
             var $row = $("<tr><td >"+(i+1)+"</td><td> <input type='text' class='inputch' name='saving' size ='6' value='"+i+"'>(<label class='inputch0'>"+i+"</label>)</td> </tr>");
          $resultTable.append($row);
       }
 var $row1 = $("<tr><td>Total</td><td><td class='totalch'> 0</td></tr>");
         var total = 0;total0=0;
   
        $resultTable.find('input.inputch').each(function() {
            total += Number($(this).val());
          });
        $resultTable.find('label.inputch0').each(function() {
              total0 += Number($(this).html());

          });
          $resultTable.find('td.totalch').html(total+' ('+total0+')'); 

         $resultTable.find('input.inputch').change(function() {
           var total = 0;total0=0;
          $resultTable.find('input.inputch').each(function() {
             total += Number($(this).val());
           });
           $resultTable.find('label.inputch0').each(function() {
               total0 += Number($(this).html());
           });
             $resultTable.find('td.totalch').html(total+' ('+total0+')');
        });

});
We use change in input box, the total will be changed only after input box lose focus.
If we want to see the immediate change, we can use keyup, i.e.
         $resultTable.find('input.inputch').keyup(function() {
OR
          $resultTable.find('input.inputch').on('input', function() {

Friday, October 31, 2014

jQuery deal with post data




To deal with .post in jQuery
var tutorialID = 1;
            $.post('data_process.php',
                {funct:'updateSITA',
                tutorialID:tutorialID,
                course_id:course_id,
                courses_offered_id:courses_offered_id,
                section:section,
                ta:ta,
                type:type,
                 status:status}, function(data){
                formatJson(data, "div#notice", null);
            });


In  data_process.php, we can hand data from post, i.e. $_POST
for example $_POST['funct']
if($_POST['funct'] == "updateSITA") {

jQuery, get value from cell




jQuery, get value from cell
1. Case 1
html:
 <td class='type'>car</td>
jQuery
var row = $(this).parent().parent();
var type = row.find('td.type').html();

2. Case 2
html
<td class='button1'> <input class='courses_offered_id'/></td>
jQuery
row.find('td input.courses_offered_id').val();

3. Case 3
html
 <td class='Ta'><select id="mySelect"><option value=" ">=No TA Assigned=</option></select></td>
jQuery
row.find('td.Ta select').val();

Thursday, October 30, 2014

jQuery, duplicate a row in a table and modify after click a button




For example in HTML
<div class='ajax_list'>
        <table class='template list'>

                <tr class='template worksheet-row' >
                    <td class='index' id='index'></td>
                    <td class='Term'></td>
                    <td class='Course'></td>
                    <td class='TutSection'><div type='text' name='TutorialSection' style='width:60px'/></td>
                    <td class='TaList'>list of TA</td>
               
                    <td class='EnrolMax'></td>
                    <td class='Status'></td>
                    <td class='type'></td>
                    <td class='button1'><input type='button' class='duplication' name='duplicate' value="duplicate"/>
                        <input type='button' class='SaveButton1' name='update' value="Save1"/>
                        <input type='hidden' class='tutorialID'/>
                        <input type='hidden' class='course_id'/>
                        <input type='hidden' class='courses_offered_id'/>
                    </td>
                </tr>
            </table>

</div>
To duplicate a row in a table and modify in jQuery via click duplicate button
    $('div.ajax_list input.duplication').live('click', function(){
           var $tr    = $(this).closest('.worksheet-row');
           var $clone = $tr.clone();

//Remove duplicate button in new row
           $clone.find('.duplication').remove();

//empty original content
            $clone.find('.TaList').empty();

//Now append a dropdown menu
 $clone.find('td.TaList').append('<select><option value=" ">=No Assigned</option></select>');
 $clone.find('td.TaList select').append('<option value="1">1</option>');
 $clone.find('td.TaList select').append('<option value="2">2</option>');
//Update button to Update
           $clone.find(':button').val('Update');

//Change cell value to marker
           $clone.find('.type').html('Marker');

//Set new row background color light green
           $clone.css('background-color','lightgreen');

//add new row in table
           $tr.after($clone);
      });     

  For passing the data to function,
$(selector).live(event,data,function)
Example
     $('div.ajax_list input.duplication').live('click',data, function(){

Wednesday, October 29, 2014

jQuery, clone a row via click add button in the same row




HTML table with add button
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
    <tr>
        <td>Name</td>
        <td>Location</td>
        <td>From</td>
        <td>To</td>
        <td>Add</td>
    </tr>
    <tr class="tr_clone">
        <td><input type="text" autofocus placeholder="who" name="who" ></td>
        <td><input type="text" autofocus placeholder="location" name="location" ></td>
        <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
        <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
        <td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
    </tr>
</table><!-- /table#table-data -->


jQuery:
$("input.tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var $clone = $tr.clone();
    $clone.find(':text').val('');
    $tr.after($clone);
});

Thursday, October 23, 2014

Add content in dropdown menu dynamically and set its default value in jQuery




 To add content in dropdown menu and set its default value in jQuery,
1) first we have a empty selection dropdown
 <select id="mySelect"><option value=" ">=No TA Assigned=</option></select>
2) Then we have JS function  myFunction() to deal with onclick to add items to dropdown, this is very useful as we can change dropdown menu dynamically.
3) We need to prevent duplication of items  dropdown, also we can set the default value
   row.find('td.Ta select').val('2');
Complete Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<style>
table {
    border-collapse: collapse;
}
table, th, td {
    border: 1px solid black;
}
</style>
<script>
function myFunction() {
   var taList = {};
   taList={
     '1': {id:1, name:'Andy'},
     '2':{id:2,name:'Jiansen'},
     '3': {id:3, name:'Tommy'} };
   var row = $('table.template tr.template');
//add other options
    for (var id0 in taList){
        var x = document.getElementById("mySelect");
        var i, add='y';
        //prevent duplication           
        for (i = 0; i < x.length; i++) {
        if(taList[id0].id ==i) add='n'
        }   
           if(add=='y')     row.find('td.Ta select').append('<option value="'+taList[id0].id+'">'+taList[id0].name+'</option>');          
      }
//Set default value, for example Andy
    row.find('td.Ta select').val('2');
}
</script>

<body>
<h1>Add content in dropdown menu and set its default value in jQuery</h1>
 <table class='template' style="border:1" >
<tr>
   <th>Courses</th><th>Pick TA</th>
<tr>
<tr class='template'>
 <td>Physics</td>   <td class='Ta'><select id="mySelect"><option value=" ">=No TA Assigned=</option></select></td>
</tr>
</table>
<button onclick="myFunction()">Click me to add TAs TA dropdown list</button>
<p id="demo"></p>
</body>
</html>