选择基于属性键的选项值

时间:2016-04-05 04:17:08

标签: javascript jquery

<option value="abc">abc</option>

我知道我可以做$('select').val('abc')但如果我有这样的话会怎么样

<option value='{"name":abc,"id":123}'>abc</option>

如何选择基于abc的{​​{1}}?

1 个答案:

答案 0 :(得分:0)

value不是有效的对象。 abc应该用引号括起来。

<option>应为

<option value='{"name":"abc","id":123}'>abc</option>
                       ^   ^

您可以使用filter()过滤掉<option>idvalue属性对象的字符串中的option元素。

然后,可以在已过滤的// Filtering all options in the select $('select option').filter(function() { var val = $(this).val(), // Get value obj = {}; // Try to parse the string to JSON try { obj = JSON.parse(val); } catch (e) { obj = {}; // Empty object if parsing fails } // Filter based on the `id` in the value return obj.id === 123; }).prop('selected', true); // Set the option as selected上使用prop('selected', true)设置为所选选项。

Demo:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
    <option value="Hello">fdsafds</option>
    <option value='{"name":"abc","id":123}'>abc</option>
</select>
data-*

由于Rayoncommented,我建议不要使用对象作为值,而是建议使用HTML5 $('option[data-id="123"]').prop('selected', true);自定义属性在元素上存储数据。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select>
    <option value="Hello" data-name="bond" data-id="007">fdsafds</option>
    <option value="something" data-name="abc" data-id="123">abc</option>
</select>
function sendEmail() {

 //setup function
 var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
 var StartRow = 3;
 var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
 var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,11);
 var AllValues = WholeRange.getValues();

 var message = "";
 //iterate loop
 for (i in AllValues) {

 //set current row
 var CurrentRow = AllValues[i];

 //define column to check if sent
 var EmailSent = CurrentRow[11];

 //if row has been sent, then continue to next iteration
 if (EmailSent == "sent") 
     continue;

 //set HTML template for information
  message +=
      "<p><b>Found by: </b>" + CurrentRow[1] + "</p>" +
      "<p><b>Title: </b>" + CurrentRow[2] + "</p>" +
      "<p><b>Agency: </b>" + CurrentRow[3] + "</p>" +
      "<p><b>Summary: </b>" + CurrentRow[4] + "</p>" +
      "<p><b>Due: </b>" + CurrentRow[5] + "</p>" +
      "<p><b>Posted: </b>" + CurrentRow[6] + "</p>" +
      "<p><b>Total Funding: </b>" + CurrentRow[7] + "</p>" +
      "<p><b>Announcement Number: </b>" + CurrentRow[8] + "</p>" +
      "<p><b>Useful Links: </b>" + CurrentRow[9] + "</p><br><br>";

  //set the row to look at
  var setRow = parseInt(i) + StartRow;

  //mark row as "sent"
  ActiveSheet.getRange(setRow, 11).setValue("sent");
}

 //define who to send grants to 
 var SendTo = "emailaddress1@gmail.com" + "," + "emailaddress2@gmail.com";

 //set subject line
 var Subject = "Grants";


  //send the actual email  
  MailApp.sendEmail({
      to: SendTo,
      cc: "",
      subject: Subject,
      htmlBody: message,
});
}