2013-10-12 67 views
0

我有一個問題,我試圖在點擊使用Javascript的「重置按鈕」後,將表單中的文本輸入更改爲黑色。HTML表單按鈕onclick使用Javascript

在HTML中使用onReset我曾考慮要解決的問題,但是,問題指出,我必須解決這個使用的Javascript只(或JQuery的如果需要的話),因此下面以下HTML不可編輯 。我已經考慮過document.forms和getElementbyID(「contact」),但不知道該從哪裏做什麼。

任何幫助讚賞謝謝!

這裏是我的HTML:

<form id="contact" action="" onsubmit="checkContactForm(this); return false;" > 
<p> 
    <label for="name">First name:</label> 
    <input name="name" id="name" onfocus="resetField(this);" /> 
</p> 
    <label for="message">Your Message:</label> 
    <textarea name="message" id="message" onfocus="resetField(this);"></textarea> 
</p> 
<p> 
    <button type="submit">Send Message</button> 
    <button type="reset">Reset Form</button> 
</p> 

這裏是我的javascript:

var requiredFields = [ "name", "message" ]; 


function resetField(theField) { 
    if (theField.value == "Error") { 
theField.value = ""; 
theField.style.color = "#000"; 
    } 
} 

function resetForm(theForm){ 
for (i in requiredFields) { 
    var fieldName = requiredFields[ i ]; 
    var theField = theForm[ fieldName ]; 
    theField.style.color = "#000"; 
    theField.value = ""; 
} 
+0

在哪兒的'resetField'功能你呼叫ING? – j08691

+0

對不起,我沒有把它添加到上面的問題 – Amber

回答

0

我試圖改變的形式向黑色後的文字輸入點擊使用Javascript的「重置按鈕」。

這可以通過jQuery中的click事件來完成。像這樣:

$('button[type="reset"]').click(function() { 
    /* change the color using 
    * $('input').css('color', '#000'); #000 is black.. 
    */ 
} 

這樣,當在重置按鈕上進行單擊時,輸入文本的顏色將變爲黑色。

jQuery代碼來複位輸入是:

$('input[type="name"]').val(''); 

注意在Val方法的單qoutes,這將消除VAL並且將與空字符串代替它。您也可以使用雙重qoutes val("")

var requiredFields = [ "name", "message" ]; 

這不是正確的方法,您應該使用input[name="name"]。但是,您可以使用簡單的jQuery來更改ID或類的輸入。

您正在使用:

resetField(this); 

這是行不通的,因爲在script標籤使用的是

resetForm 

而且,由於這些兩者不一致,沒有腳本可以運行!

祝你好運,

+0

對不起,我也有我的代碼resetfield,我沒有在上面添加它,因爲我認爲這是無關緊要的問題(現在增加)。我會很快嘗試你的解決方案,謝謝。 – Amber

+0

哦,好的!那麼現在有什麼問題?代碼很好..它在哪裏崩潰? –

0

解決方案低於

HTML代碼

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="ISO-8859-1"> 
     <title>Insert title here</title> 
    </head> 
    <body> 
     <form action="nothing" id="testForm"> 
      <label for="textInput">Text Input</label> 
      <input type="text" id="textInput" name="textInput"> 
      <label for="textAreaInput">Text Area Input</label> 
      <textarea rows="10" cols="20" id="textAreaInput" name="textAreaInput"></textarea> 
      <input type="submit" id="submitButton"> <input type="reset" id="resetButton"> 
     </form> 
     <script type="text/javascript" src="scripts/lib/jquery-2.0.3.min.js"></script> 
     <script type="text/javascript" src="scripts/app/test.js"></script> 
    </body> 
</html> 

Javascript代碼使用jQuery

$(document).ready(function() { 
     $("#resetButton").click(function() { 
      // change color of all textarea fields to red 
      $("#testForm textarea").css('color', 'red'); 
      // change color of all text input fields to red 
      $("#testForm input[type='text']").css('color', 'red'); 
      return false; 
     }); 
    } 
); 
相關問題