2013-10-02 56 views
0

在我當前的項目中,我需要對輸入,選擇和其他表單字段的變量選擇進行「取整」並將它們作爲表單提交。爲了做到這一點,我正在創建一個<form>元素。沿着jQuery動態表單提交錯誤

HTML的東西線

<a id="fire" href="#" title="submit form">Submit form</a> 
<input id='inpQ' name='q' type='text' required/> 

JS

$('#fire').click(function (event) { 
    event.preventDefault(); 
    var opts = { 
     'action': 'http://www.google.com/search', 
     'target': '_blank' 
    } 
    var newForm = $('<form>', opts).append($('#inpQ').clone()); 
    newForm.submit(); 
}); 

我要解釋一下,我需要保留原來的元素,而不僅僅是隔離它們使用的形式 - 因此.clone()。

對於工作演示中看到this fiddle

這工作 - 但只到一個點。這些問題我都遇到

  • WebKit瀏覽器:工作,但是禁令要求的「inpQ值是由瀏覽器忽略。
  • 在Firefox和IE10中,它根本不起作用。在後者中,我得到控制檯錯誤沿着訪問被拒絕的行,$是未定義的。在Firefox中沒有錯誤,但是......沒有任何反應。

也許有人在這裏可以解釋一些這些問題?

+0

29的Chrome OS X 10.8.4,工程完全按照自己的需要,無可厚非happended – jasonslyvia

+0

運說工作鉻在IE 10不工作 –

+0

瀏覽器在Windows上運行得很好,但也需要*** ***被忽略。你是否告訴我它在OS X中不被忽略? – DroidOS

回答

2

你可以試試這樣

$('#fire').click(function(event) { 
    event.preventDefault(); 
    var url = 'http://www.google.com/search'; 
    var opts = { 'action':url, 'target':'_blank', 'style':'display:none' }; 
    var inpQ = $('#inpQ').clone(); 
    var newForm =$('<form/>', opts).append(inpQ); 

    $('body').append(newForm); 
    newForm.trigger('submit').remove(); 
}); 

Working Example.(在Chrome和FF測試)的東西。

更新: 使用required屬性,這樣,你不能這樣做,你必須保持表單的inputfocusable/visible,使之與html5 required attribute的工作,你可以用js驗證使用的class=required形式在提交的輸入,像(也適用於IE-10):

$(function(){ 

    $('#fire').click(function(event) { 
     event.preventDefault(); 
     var url = 'http://www.google.com/search'; 
     var opts = { 
      'id':'vForm', 
      'action':url, 
      'target':'_blank', 
      'style':'display:none' 
     }; 
     var inpQ = $('#inpQ').clone(); 
     var newForm =$('<form/>', opts).append(inpQ); 

     $('body').append(newForm); 
     newForm.trigger('submit'); 
     newForm.remove(); 
    }); 

    $(document).on('submit', '#vForm', function(e){ 
     $('#vForm .rerquired').each(function(){ 
      if(!this.value.length) { 
       e.preventDefault(); 
       alert(this.name +' is a required field'); 
       $('#vForm').remove(); 
       return false; 
      } 
     }); 
    }); 
}); 

Internet explorer-10它不工作,因爲jQuery版本,但現在它的工作原理。

Working Example.(測試IE-10,FFChrome)。

+0

你願意告訴我投票原因:所以每個人(包括我)都能確定這個代碼有什麼問題。 –

+0

@DroidOS,這有什麼問題?你能解釋一下嗎? –

+0

@DroidOS,你應該解釋下來投票這個答案,因爲這是工作。 –