2013-07-22 73 views
0

來存儲和檢索JSON值我在我的html兩個文本框(goalText和goalText1)和一個按鈕(goalreach)。 我的目的:當我在1個文本框(goalText)輸入數字值時,它應該被轉換到JSON和被存儲。所以即使在運行應用程序的5天后,它也應該被存儲。現在,當我輸入數字值時,在其他文本框(goalText1)中匹配,我只是顯示消息匹配。這是演示,我試着讓我知道值可以存儲在json中,並且可以在必要時檢索。我寫的代碼如下:無法的jQuery

$("#goalreach").click(function() { 
    var contact = new Object(); 
    contact.goalDist = "$("#goalText.value ").val()"; 
    var jsonText = JSON.stringify(contact); 
    if (jsonText == ($("#goalText1.value").val())) { 
     document.getElementById('divid').innerHTML = 'Match'; 
    } 
}); 

我知道,我做了支架的許多簡單的錯誤和「過,但我是一個新手,如果你能幫助我

回答

0

首先,你必須用來比較兩個對象或2串,並在goalDist,你應該存儲值(順便說一句,你得到的jQuery對象與$("#goalText")somejQueryObject.val()值而且這通常相當於document.getElementById("goalText").value) ...

這是可以做到這樣的:

$("#goalreach").click(function() { 
    // Create an object with the single property "goalDist" 
    var contact = { goalDist : $("#goalText").val() }; 

    // Makes it be a string (it will in this simple example : `"{"goalDist":<the value of goalTest>}"` 
    var jsonText = JSON.stringify(contact); 

    // Creates a string from an equivalent object bound on the second field 
    var jsonText2 = JSON.stringify({ goalDist : $("#goalText2").val() }); 

    // Compares the 2 strings 
    if (jsonText === jsonText2) { 
     document.getElementById('divid').innerHTML = 'Match'; 
    } 
}); 
+0

我不知道,爲什麼每個人的代碼是行不通的。難道我做任何愚蠢的錯誤?我的div id爲「DIVID」,是.innerHTML線是否正確? 我寫它。一個JavaScript和HTML文件,我已經添加源本JS,我覺得我在其他兩不誤 – user2387900

+0

我已經取得了一些的jsfiddle:。http://jsfiddle.net/SFGmS/您可以測試代碼。JavaScript是大小寫敏感的:小心你的HTML代碼的ID ... –

+0

做,做,done..thankss的 – user2387900

0

請嘗試以下。代碼:

$("#goalreach").click(function() { 
    var contact = new Object(); 
    contact.goalDist = $("#goalText").val(); 
    var jsonText = JSON.stringify(contact); 
    if (jsonText == ($("#goalText1").val())) { 
     document.getElementById('divid').innerHTML = 'Match'; 
    } 
}); 

OR

$("#goalreach").click(function() { 
    var goalText = $("#goalText").val(); 
    var goalText1 = $("#goalText1").val(); 
    if (goalText == goalText1) { 
     document.getElementById('divid').innerHTML = 'Match'; 
    } 
}); 
+0

不工作.... – user2387900

+0

確保您taxtbox具有在jQuery的使用id屬性。 –

+0
0

試試這個

$("#goalreach").click(function() { 

var contact = new Object(); 

var goalDist = '$("#goalText.value").val()'; 
var jsonText = JSON.stringify(contact.goalDist); 

if(jsonText==($("#goalText1.value").val())) 
{ 
    document.getElementById('divid').innerHTML = 'Match'; 
} 
}); 
+0

不工作.. :( – user2387900