เงื่อนไขการ show/hide textbox มาให้กรอกข้อมูล ในการ clone หลายแถว

ถาม-ตอบ แนะนำไอเดียว โค้ดตัวอย่าง แนวทาง วิธีแก้ปัญหา เงื่อนไขการ show/hide textbox มาให้กรอกข้อมูล ในการ clone หลายแถว

เงื่อนไขการ show/hide textbox มาให้กรอกข้อมูล ในการ clone หลายแถว

ตามรูปนะคะ คือ เวลาเลือก select ประเภท = เช่า จะขึ้น textbox ระยะเวลาการเช่า มาให้กรอกข้อมูล
แต่พอกดปุ่ม บวก เพื่อจะเพิ่มสินค้าอีกตัว ยังไม่ทันเลือกประเภท มันก็ clone ตัว textbox มาด้วยค่ะ

codeการ clone
<script language="JavaScript">
$(document).ready(function(){
    $("#addRow").click(function(){
        var html = $(".tramount:last").html();
        var last_id = parseInt($(".tramount:last").attr("id").split("_")[1]);
        var new_id = last_id+1;
        var newRow = '<tr class="tramount" id="tramount_'+new_id+'">'; 
        newRow += html.replace(new RegExp("_"+last_id,"g"), "_"+new_id);
        newRow += "</tr>";
        $("#tblamount tbody").append(newRow);
    });
    $("#removeRow").click(function(){
        if($(".tramount").length > 1) $(".tramount:last").remove()
    });
    $('input[name="cost[]"], input[name="amount[]"]').change(function(){
        var total = 0.0;
        $(".tramount").each(function(){
            var now_id = parseInt($(this).attr("id").split("_")[1]);
            var cnt = parseInt($("#amount_"+now_id).val());
            var price = parseFloat($("#cost_"+now_id).val());
            var row = (cnt*price);
            if(row!= NaN && row>0) total += row;            
        });
        $("#sum").val(total);        
    });
});
</script>
code การ show/hide textbox 
<script language="javascript">
$(document).ready(function() {
	$('#rentPrice').hide(); //hide field on start
 
	$('#type_1').change(function() {
 
	 var $index = $('#type_1').index(this);
 
	 if($('#type_1').val() == 'เช่า') { //if this value is NOT selected
	 $('#rentPrice').show(); //this field is hidden
	 } 
	 else {
	 $('#rentPrice').hide();//else it is shown
 
	 }
        });
 });
</script>
อยากรู้ว่าจะทำยังไง ให้ไม่ clone มาทั้งหมดค่ะ ให้โชว์ textbox เฉพาะตอนเลือก select ประเภท = เช่า เท่านั้น


Saranya2532 223.204.255.xxx 25-08-2014 14:06:32

คำแนะนำ และการใช้งาน

สมาชิก กรุณา ล็อกอินเข้าระบบ เพื่อตั้งคำถามใหม่ หรือ ตอบคำถาม สมาชิกใหม่ สมัครสมาชิกได้ที่ สมัครสมาชิก


  • ถาม-ตอบ กรุณา ล็อกอินเข้าระบบ
  • เปลี่ยน


    ( หรือ เข้าใช้งานผ่าน Social Login )

 ความคิดเห็นที่ 1
ให้ใส่ css class ไปใน ตัว input ตัวที่จะให้ซ่อนหรือแสดงตามเงื่อนไข
แล้ว ส่งให้ย้อนไป ที่แถว แล้วไปหา css ตัวนั้น :ซ่อนตามเงื่อนไข

เช่น 

         if(i_select=="A"){
            $(this).parents("tr").find(".css_more").show();   
         }else{
             $(this).parents("tr").find(".css_more").hide();   
         }


เท่าที่ดูตามโค้ด ยังใช้ id กับ class ไม่ค่อยถูกเท่าไหร่ พยายามใช้ css class แทน id
รหือ .css มากกว่า #id เวลาใช้กับ jquery

ลองดูโค้ดตัวอย่างนี้ เอาไปประยุกต์เพิ่มเติมได้


ประเภท ยี่ห้อ ชื่อสินค้า



ไฟล์ index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <style type="text/css">
    .css_more{
        display: none;
    }
    </style>
</head>
<body>
   
    <br>
    <div style="margin:auto;width:90%;">
    <form role="form" method="post" action="show.php">
      <table class="table table-striped">
          <tr class="active">
              <th class="text-center">ประเภท</th>
              <th class="text-center">ยี่ห้อ</th>
              <th class="text-center">ชื่อสินค้า</th>
              <th width="130" class="text-center"></th>
          </tr>
          <tbody class="place-datarow">
              <tr class="datarow" >
                  <td>
                    <select name="type_product[]" class="form-control css_i_select">
                        <option value="">Select Type</option>
                        <option value="A">Type A</option>
                        <option value="B">Type B</option>
                    </select>  
                      
                  </td>
                  <td>
                    <select name="brand_product[]" class="form-control">
                        <option value="">Select Brand</option>
                        <option value="AAA">Brand AAA</option>
                        <option value="BBB">Brand BBB</option>
                    </select>                  
                  </td>
                  <td>
                  <input type="text" class="form-control" name="name_product[]" >
                  </td>
                  <td>
<input type="text" class="form-control css_more" name="more_data[]">                  
                  </td>
              </tr>
          </tbody>
      </table>
      <br>
      <table class="table">
          <tr>
              <td width="50" class="tex-center">
               <button id="addRow" type="button" class="btn btn-info">+</button>      
              </td>
              <td width="50" class="tex-center">
               <button id="removeRow" type="button" class="btn btn-danger">-</button>      
              </td>
              <td class="text-right">
               <button type="submit" class="btn btn-success">Submit</button>
                  
              </td>
          </tr>
      </table>
      </form>
    </div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
<script type="text/javascript" src="script.js"></script>         
</body>
</html>


ไฟล์ script.js

$(function () {
    
     $(".css_i_select").on("change",function(){  
        var i_select=$(this).val();
         if(i_select=="A"){
            $(this).parents("tr").find(".css_more").show();   
         }else{
             $(this).parents("tr").find(".css_more").hide();   
         }
    });
    
    
    $("#addRow").on("click",function(){   
        // ส่วนของการ clone ข้อมูลด้วย jquery clone() ค่า true คือ    
        // การกำหนดให้ ไม่ต้องมีการ ดึงข้อมูลจากค่าเดิมมาใช้งาน    
        // รีเซ้ตเป็นค่าว่าง ถ้ามีข้อมูลอยู่แล้ว ทั้ง select หรือ input    
      
        $(".datarow:eq(0)").clone(true)     
        .find("input").attr("value","").end()    
        .find("select").attr("value","").end()  //   
        .appendTo($(".place-datarow"));     
          
    }); 
    
    $("#removeRow").on("click",function(){    
        // // ส่วนสำหรับการลบ    
        if($(".place-datarow tr").size()>1){ // จะลบรายการได้ อย่างน้อย ต้องมี 1 รายการ    
            $(".place-datarow tr:last").remove(); // ลบรายการสุดท้าย    
        }else{    
            // เหลือ 1 รายการลบไม่ได้    
            alert("ต้องมีรายการข้อมูลอย่างน้อย 1 รายการ");    
        }    
    });    
});


ไฟล์ show.php ทดสอบ

<pre>
    <?php print_r($_POST); ?>
    
</pre>


ninenik 110.168.67.xxx 25-08-2014
 ความคิดเห็นที่ 2
ตอนนี้หนูใช้โค้ด clone เป็นแบบ autocomplete ด้วย

$(document).ready(function(){
	$(".css_i_select").on("change",function(){  
        var i_select=$(this).val();
         if(i_select=="เช่า"){
            $(this).parents("tr").find(".css_more").show();   
         }else{
             $(this).parents("tr").find(".css_more").hide();   
         }
    });
    // Use the .autocomplete() method to compile the list based on input from user
    $('#brand').autocomplete({
        source: 'autocomplete/autoProducts/data/item-data.php',
        minLength: 1,
        select: function(event, ui) {
            var $itemrow = $(this).closest('tr');
                    // Populate the input fields from the returned values
					$itemrow.find('#codeST').val(ui.item.codeST);
                    $itemrow.find('#brand').val(ui.item.brand);
					$itemrow.find('#type').val(ui.item.type);
                 		       $itemrow.find('#unit').val(ui.item.unit);

                    // Give focus to the next input field to recieve input from user
					$('#typeQT').focus();
                    $('#detail').focus();
					$('#price').focus();
					$('#quantity').focus();
					$('#discount').focus();
					

            return false;
	    }
    // Format the list menu output of the autocomplete
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.brand + " - " + item.codeST + "</a>" )
            .appendTo( ul );
    };

    // Get the table object to use for adding a row at the end of the table
    var $itemsTable = $('#itemsTable');

    // Create an Array to for the table row. ** Just to make things a bit easier to read.
    var rowTemp = [
        '<tr class="item-row">',
            '<td><a id="deleteRow"><img src="autocomplete/autoProducts/images/icon-minus.png" alt="Remove Item" title="Remove Item"></a></td>',
			'<td><select name="typeQT[]" id="typeQT" class="form-control" tabindex="1"><option value="">เลือกประเภท</option><option value="ขาย">ขาย</option><option value="เช่า">เช่า</option><option value="ค่าบริการ">ค่าบริการ</option></select></td>',
            '<td><input name="codeST[]" type="hidden" class="form-control" id="codeST"/><input name="brand[]" value="" class="form-control" id="brand" tabindex="2"/></td>',
			'<td><input name="type[]" value="" class="form-control" id="type" tabindex="3" /></td>',
			
			'<td><input name="unit[]" value="" class="form-control" id="unit" tabindex="12"/></td>',
			'<td><input name="price[]" value="" class="form-control" id="price" tabindex="13" OnKeyPress="return chkNumber(this);"/></td>',
			'<td><input name="discount[]" value="" class="form-control" id="discount" tabindex="14" OnKeyPress="return chkNumber(this);"/></td>',
									  
        '</tr>'
    ].join('');

    // Add row to list and allow user to use autocomplete to find items.
	
	
    $("#addRow").bind('click',function(){

        var $row = $(rowTemp);

        // save reference to inputs within row
		var $codeST 	        = $row.find('#codeST');
        var $brand 	        = $row.find('#brand');
		var $type 	        = $row.find('#type');
        	var $typeQT 	    = $row.find('#typeQT');
		var $unit 	        = $row.find('#unit');
             var $price	        = $row.find('#price');
        var $quantity	    = $row.find('#quantity');
		var $discount 	    = $row.find('#discount');

        if ( $('#brand:last').val() !== '' ) {

            // apply autocomplete widget to newly created row
            $row.find('#brand').autocomplete({
                source: 'autocomplete/autoProducts/data/item-data.php',
                minLength: 1,
                select: function(event, ui) {
					$codeST.val(ui.item.codeST);
                    $brand.val(ui.item.brand);
					$type.val(ui.item.type);
                    $transmission.val(ui.item.transmission);
					$unit.val(ui.item.unit);
					

                    // Give focus to the next input field to recieve input from user
                     $typeQT.focus();
					 $detail.focus();
					 $price.focus();
					 $quantity.focus();
					 $discount.focus();

                    return false;
                }
            }).data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.brand + " - " + item.codeST + "</a>" )
                    .appendTo( ul );
            };
            // Add row after the first row in table
            $('.item-row:last', $itemsTable).after($row);
            $($brand).focus();

        } // End if last brand input is empty
        return false;
    });

    $('#brand').focus(function(){
        window.onbeforeunload = function(){ return "ทำรายการใบเสนอราคา"; };
    });

}); // End DOM


	// Remove row when clicked
	$("#deleteRow").live('click',function(){
		$(this).parents('.item-row').remove();
        // Hide delete Icon if we only have one row in the list.
        if ($(".item-row").length < 2) $("#deleteRow").hide();
	});
	

ถ้าใส่แบบนี้ จะขึ้น textbox เวลาเลือก select "เช่า"  แต่ไม่สามารถกด  + เพิ่มข้อมูลได้  ไม่ทราบว่าต้องแก้ตรงไหนค่ะ



saranya2532 223.204.255.xxx 26-08-2014 14:04
 ความคิดเห็นที่ 3
คงแนะนำไม่ได้ ต้องดูการทำงานรวม
แต่ดูจากวิธีการเขียนโค้ด เหมือนจะเขียนยากไป
การเพิ่มแถว ถ้าใช้การ clone ก็จะอ้างอิงกับ html ด้วย
แต่การ clone แบบใช้ตัวแปร ก็คงเป็นปํญหาอีกแบบหนึ่ง


ninenik 58.11.234.xxx 26-08-2014
 ความคิดเห็นที่ 4
แล้วถ้าเป็นการ clone ข้อมูลแบบธรรมดา 

ถ้าต้องการ จะ add row ข้อมูลที่เป็น datetimepicker ซึ่งโค้ดมาจาก http://xdsoft.net/jqplugins/datetimepicker/

<td align="center">
		<input name="buyDate[]" type="text" id="datetimepicker" class="form-control" /></td>
<td align="center">
		<input name="contractDate[]" type="text" id="datetimepicker2" class="form-control" /></td>

แล้วจะ  addRow 
ยังไงค่ะ 

  $("#addRow").on("click",function(){   
        // ส่วนของการ clone ข้อมูลด้วย jquery clone() ค่า true คือ    
        // การกำหนดให้ ไม่ต้องมีการ ดึงข้อมูลจากค่าเดิมมาใช้งาน    
        // รีเซ้ตเป็นค่าว่าง ถ้ามีข้อมูลอยู่แล้ว ทั้ง select หรือ input    
      
        $(".datarow:eq(0)").clone(true)     
        .find("input").attr("value","").end()    
        .find("select").attr("value","").end()  //   
        .appendTo($(".place-datarow"));     
          
    }); 

ดูจากที่อื่นมีแต่ datepicker ไม่มีที่เป็น datetimepicker 
เช่น http://jsfiddle.net/chiragraninga/MMmyU/
.removeClass('hasDatepicker');  ตรงนี้ก็ไม่เข้าใจว่ามาจากไหนอ่ะค่ะ 


saranya2532 223.204.255.xxx 28-08-2014 16:42
 ความคิดเห็นที่ 5
โค้ดตัวอย่าง จะใช้ กับ jquery ui datepicker โค้ดจึงไม่เหมือนกัน 

ส่วนตัว datetimepicker ที่เนะนำมา สวยงามมาก เรียบง่าย น่าใช้ทีเดียว

ดูการประยุกต์จากบทความนี้

แนะนำ DateTimePicker เรียบง่าย และสวย น่าใช้มาก  


ninenik 1.46.209.xxx 29-08-2014
 ความคิดเห็นที่ 6
ขอบคุณมากค่ะ  smileysmiley


saranya2532 223.204.255.xxx 29-08-2014 09:25
 ความคิดเห็นที่ 7
แล้วถ้า เพิ่มแถววันที่ อีกอัน

..size()-1;  ต้องเปลี่ยนเป็นอะไรค่ะ หนูลองเปลี่ยน -2,-3,-4,-0 ก็แล้ว ก็ไม่ได้อ่ะค่ะ

var lastIndex2=$(".css_datetime_picker").size()-1; // หา index ของตัว input ล่าสุด  
        var newId2="id_datetime_picker"+lastIndex2;
        var objID2="#"+newId2;
        var placeParent2=$(".css_datetime_picker:eq("+lastIndex2+")").parents("td");   
 // แทนด้วย input ใหม่ ทับตัวเก่าไปเลย
 $(placeParent2).html("<input type="text" class="form-control css_datetime_picker" name="date_product2[]" >");     
        $(".css_datetime_picker:eq("+lastIndex2+")")
        .attr("id", newId2) // - กำหนด id เป็นค่าใหม่
        .unbind(); // - ยกเลิกการจัดการทั้งหมด ที่ได้มาจากตัว clone        
        $(objID2).datetimepicker(); // - เรียกใช้ datetimepicker() ใหม่อีกครั้ง		


saranya2532 223.204.255.xxx 29-08-2014 10:41
 ความคิดเห็นที่ 8
นึกภาพไม่ออก


ninenik 110.168.68.xxx 29-08-2014
 ความคิดเห็นที่ 9

ถ้าตามโค้ด จะเลือก datetimepicker  ได้เฉพาะ วันที่หมดสัญญา ใช่ไม๊ค่ะ
แล้วถ้าจะให้เลือก datetimepicker ได้กับ วันที่ซื้อ/เช่า ด้วยอ่ะค่ะ 
ต้องเปลี่ยนแปลงโค้ดตรงไหนค่ะ

$(function () {
    
    $("#id_datetime_picker0").datetimepicker(); 

$("#addRow").on("click",function(){   
        // ส่วนของการ clone ข้อมูลด้วย jquery clone() ค่า true คือ    
        // การกำหนดให้ ไม่ต้องมีการ ดึงข้อมูลจากค่าเดิมมาใช้งาน    
        // รีเซ้ตเป็นค่าว่าง ถ้ามีข้อมูลอยู่แล้ว ทั้ง select หรือ input    
      
        $(".datarow:eq(0)").clone(true)     
        .find("input").attr("value","").end()    
        .find("select").attr("value","").end()  //   
        .appendTo($(".place-datarow"));     
        var lastIndex=$(".css_datetime_picker").size()-1; // หา index ของตัว input ล่าสุด  
        var newId="id_datetime_picker"+lastIndex;
        var objID="#"+newId;
        var placeParent=$(".css_datetime_picker:eq("+lastIndex+")").parents("td");    
        // แทนด้วย input ใหม่ ทับตัวเก่าไปเลย
         $(placeParent).html("<input type="text" class="form-control css_datetime_picker" name="date_product[]" >");     
        $(".css_datetime_picker:eq("+lastIndex+")")
        .attr("id", newId) // - กำหนด id เป็นค่าใหม่
        .unbind(); // - ยกเลิกการจัดการทั้งหมด ที่ได้มาจากตัว clone        
        $(objID).datetimepicker(); // - เรียกใช้ datetimepicker() ใหม่อีกครั้ง          
          
    }); 

เพราะหนูลองเพิ่มโค้ดแล้ว แต่มันไม่ได้ เลยสงสัยว่าต้องเปลี่ยนค่าตรง .size()-1;  หรือเปล่าค่ะ


saranya2532 223.204.255.xxx 29-08-2014 13:42
 ความคิดเห็นที่ 10
ใน html ให้เพิ่ม s เข้าไปในรายการอีกอันที่เพิ่มเข้ามาทั้ง class และ id  (css_datetime_pickers  และ  id_datetime_pickers0 )
เช่น

<input type="text" class="form-control css_datetime_pickers" name="date2_product[]" value="" id="id_datetime_pickers0" >  

ใน javascript ให้ทำคล้ายส่วนเดิม แต่เพิ่มอีกชุดที่เป็นตัวเติม s

ส่วนตอนโหลดตอนแรก 

$("#id_datetime_picker0").datetimepicker();   
$("#id_datetime_pickers0").datetimepicker();   


ส่วนที่เพิ่มแถว

    $(".datarow:eq(0)").clone(true)
        .find("input").attr("value", "").end()
        .find("select").attr("value", "").end() //     
    .appendTo($(".place-datarow"));
    var lastIndex = $(".css_datetime_picker").size() - 1; // หา index ของตัว input ล่าสุด    
    var newId = "id_datetime_picker" + lastIndex;
    var newIds = "id_datetime_pickers" + lastIndex;
    var objID = "#" + newId;
    var objIDs = "#" + newIds;
    var placeParent = $(".css_datetime_picker:eq(" + lastIndex + ")").parents("td");
    var placeParents = $(".css_datetime_pickers:eq(" + lastIndex + ")").parents("td");
    // แทนด้วย input ใหม่ ทับตัวเก่าไปเลย  
    $(placeParent).html("<input type=\"text\" class=\"form-control css_datetime_picker\" name=\"date_product[]\" >");
    $(placeParents).html("<input type=\"text\" class=\"form-control css_datetime_pickers\" name=\"date2_product[]\" >");
    $(".css_datetime_picker:eq(" + lastIndex + ")")
        .attr("id", newId) // - กำหนด id เป็นค่าใหม่  
    .unbind(); // - ยกเลิกการจัดการทั้งหมด ที่ได้มาจากตัว clone    
    $(".css_datetime_pickers:eq(" + lastIndex + ")")
        .attr("id", newIds) // - กำหนด id เป็นค่าใหม่  
    .unbind(); // - ยกเลิกการจัดการทั้งหมด ที่ได้มาจากตัว clone    
    $(objID).datetimepicker(); // - เรียกใช้ datetimepicker() ใหม่อีกครั้ง
    $(objIDs).datetimepicker(); // - เรียกใช้ datetimepicker() ใหม่อีกครั้ง





ninenik 124.120.62.xxx 29-08-2014
1 2 Next






เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ