2015-09-21 2 views
-1

Привет Я использую codeigniter На моей странице просмотра У меня есть abutton, чтобы динамически добавлять строку таблицы, и у меня есть кнопка отправки формы. Когда я нажимаю кнопку добавления, моя форма отправляется. Как остановить отправку формы при нажатии кнопки «Добавить» и как отправить форму при нажатии кнопки «Отправить».Когда я нажимаю любую кнопку на моей странице просмотра, форма отправляется

<html> 

<head> 
    <meta charset="UTF-8"> 

<link href="<?php echo base_url(); ?>assets/css/elfanto_css.css" rel="stylesheet"> 
    <link href="<?php echo base_url(); ?>assets/css/style.css" rel="stylesheet"> 
    <link href="<?php echo base_url(); ?>assets/css/demo.css" rel="stylesheet"> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
<script type='text/javascript' src='//code.jquery.com/jquery-compat-git.js'></script> 


<script type='text/javascript'> 
var baseurl='<?php echo base_url(); ?>'; 
$(function() { 
    $('#test').on('change', 'input[name="pid[]"]', function() { 
     var indexOfTheChangedRow = $(this).closest("tr").index(); 
     get_values(this.value, indexOfTheChangedRow); 
    }); 
}); 


function get_values(val,rowIndex) 
{ 
$.ajax({ 
    url: baseurl + 'admin/billing/getdetails', 
    type: 'post', 
    data: { 
     val: val 
    }, 
    success: function (indexOfTheChangedRow, response) { 
     if (response != "") { 
      var json = jQuery.parseJSON(response), 
       rowToUpdate = $("#test tr:nth-child(" + (indexOfTheChangedRow + 1) + ")"); 

      // add the changed row as the context to restrict the search for the classes to this one row only 
      $('.description', rowToUpdate).val(json.description); 
      $('.type', rowToUpdate).val(json.type); 
      $('.qty_used', rowToUpdate).val(json.qty_used); 
      $('.qty_prch', rowToUpdate).val(json.qty_prch); 

     } 
    }.bind(window, rowIndex), 
    error: function (response) { 
     alert("error"); 
    } 
}); 
} 
function loadgrandtotal() { 
    var sum = 0; 
    $('.subtot').each(function() { 
     var prodprice = Number($(this).text()); 
     sum = sum + prodprice; 
    }); 
    $("#totalrst").text(sum.toFixed(2)); 
} 


function displayResult() { 
<?php 

     $attributes = array('class' => 'form-horizontal', 'id' => ''); 
     $options_employee = array('' => "Select"); 
     foreach ($employee as $row) 
     { 
     $options_employee[$row['first_name']] = $row['first_name']; 
     } 
    $dropdown = form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"'); 

     ?> 

    var complex = <?php echo json_encode($dropdown); ?>; 

    var row = document.getElementById("test").insertRow(-1); 
    row.innerHTML = '<td><div>'+complex+'</div></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" style="width:35px;"/></td><td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td><td><input type="text" class="type" value="" style="width:45px;"/></td><td><input type="text" class="qty_prch" value="" style="width:45px;"/></td><td><input type="text" class="qty_used" value="" style="width:45px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td><input type="text" value="" style="width:70px;"/></td><td class="subtot"><input type="text" value="" style="width:70px;"/></td>'; 
} 
</script> 
</head> 
<body bgcolor="#CCCCCC"> 
      <p><img src="../assets/img/ticket_page/Client.svg"> <input type="text" value=""/></p> 
        <!-- Your Content Here --> 
         <?php 

     $attributes = array('class' => 'form-horizontal', 'id' => ''); 
     $options_employee = array('' => "Select"); 
     foreach ($employee as $row) 
     { 
     $options_employee[$row['first_name']] = $row['first_name']; 
     } 
echo form_open('admin/employee/add'); /*I open my form here*/ 
     ?> 
      <div id="form"> 
      <!-- div form starts here.its for add table --> 
      <table id="test"> 
      <thead> 
      <tr> 
      <td style="width:80px;"><img src="../assets/img/ticket_page/employee.svg"></td> 
      <td style="width:35px;"><img src="../assets/img/ticket_page/start_time.svg"></td> 
      <td style="width:35px;"><img src="../assets/img/ticket_page/id.svg"></td> 
      <td style="width:145px;"><img src="../assets/img/ticket_page/Description.svg"></td> 
      <td style="width:45px;"><img src="../assets/img/ticket_page/Type.svg"></td> 
      <td style="width:45px;"> <img src="../assets/img/ticket_page/qty_prch.svg"></td> 
      <td style="width:45px;"> <img src="..assets/img/ticket_page/qty_used.svg"></td> 
      <td style="width:70px;"> <img src="../assets/img/ticket_page/Price.svg"></td> 
      <td style="width:70px;"> <img src="../assets/img/ticket_page/discount.svg"></td> 
      <td style="width:70px;"> <img src="../assets/img/ticket_page/Tax.svg"></td> 
      <td style="width:70px;"> <img src="../assets/img/ticket_page/Total_01.svg"></td> 
      </tr> 
      </thead> 
      <tbody> 
      <tr> 
      <td><?php echo form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');?></td> 
      <td><input type="text" name="start_time[]" value="" style="width:35px;"/></td> 
      <td><input type="text" name="pid[]" value="" style="width:35px;"/></td> 
      <td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td> 
      <td><input type="text" name="type[]" class="type" style="width:45px;"/></td> 
      <td><input type="text" name="qty_prch[]" class="qty_prch" style="width:45px;"/></td> 
      <td><input type="text" name="qty_used[]" class="qty_used" style="width:45px;"/></td> 
      <td><input type="text" name="price[]" class="price" style="width:70px;"/></td> 
      <td><input type="text" name="discount[]" class="discount" style="width:70px;"/></td> 
      <td><input type="text" name="tax[]" class="tax" style="width:70px;"/></td> 
      <td class="subtot"><input type="text" name="total[]" class="total" style="width:70px;"/></td> 

      </tr> 
      </tbody> 



      </table> 

      <div id="add_row"> 
     <button onClick="displayResult()" class="add_r"></button> 
       </div> 
<button id="btn" type="submit">SAVE</button>/*this my actual submit button*/ 
      <button id="btn" type="reset">CANCEL</button> 



     <?php echo form_close(); ?> /*Here I close my form*/  
    </body> 
</html> 

Может кто-нибудь мне помочь? Мне нужно отправить свою форму, только когда я нажму кнопку «Отправить». Пожалуйста, помогите мне решить проблему.

ответ

2

Дайте атрибут type вашей кнопке, который не позволит им запускать действие отправки, когда в обработчике события возникает исключение.

Вы используете элемент кнопки HTML5. Помните, что эта кнопка имеет по умолчанию поведение типа отправки, как указано в спецификации W3. Check this.

<button type="button" onClick="displayResult()" class="add_r"></button> 
+0

Почему пустые голоса, пожалуйста? –

+0

Пожалуйста, восстановите свой ответ, он кажется правильным ....... – Akki619

+0

@ Akki619 да я просто сделал! Я не понимаю, почему голоса вниз в первую очередь? –

0

Вы могли бы действительно изменить представить кнопку «типа», но в случае, если вы все еще хотите, чтобы отправить форму позже, используя представить, не меняйте его. Чтобы предотвратить отправку формы по умолчанию, добавить в Javascript:

$("form").submit(function(e) { 
    e.preventDefault(); 
} 

Если вы все еще хотите, чтобы отправить форму, вы можете поместить preventDefault внутри, если заявление.

+0

why preventDefault используется? Каково его использование? – Anu

+1

preventDefault останавливает отправку формы по умолчанию, когда нажата кнопка отправки. –

Смежные вопросы