Get and set selected option using template

时间:2015-10-30 21:27:48

标签: javascript jquery html templates

How could I change selected option for dropdown list using javascript or jQuery?

<select id ="someId" name="someName">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select><br>

<label>item1:</label>
<input type="text" name="item1" value= <%= someValue %>><br>
<label>Line item2:</label>
<input type="color" name="item2" value= <%= someValue1 %>><br>
<label>item3:</label>
<input type="number" name="item3" min=0 value= <%= someValue2 %>><br>
<label>item4:</label>
<input type="color" name="item4" value= <%= someValue3 %>><br>

I had this html saved in a variable called template. How could I get and set the selected option in dropdown list, so the result will be the same template with one of three options selected. Thank you in advance. Example of result:

<select id ="someId" name="someName">
    <option selected>One</option>
    <option>Two</option>
    <option>Three</option>
</select><br>

<label>item1:</label>
<input type="text" name="item1" value= <%= someValue %>><br>
<label>Line item2:</label>
<input type="color" name="item2" value= <%= someValue1 %>><br>
<label>item3:</label>
<input type="number" name="item3" min=0 value= <%= someValue2 %>><br>
<label>item4:</label>
<input type="color" name="item4" value= <%= someValue3 %>><br>

4 个答案:

答案 0 :(得分:0)

There is a similar JavaScript way to do this:

// code for setting item_id
var template = '<select id ="someId" name="someName"> \
    <option ';
if(item_id == 1) {
    template += 'selected';
}
template += ' >One</option> <option ';
if(item_id == 2) {
    template += 'selected';
}
template += ' >Two</option> <option ';
if(item_id == 3) {
    template += 'selected';
}
template += ' >Three</option> \
</select><br> \
<label>item1:</label> \
<input type="text" name="item1" value= <%= someValue %>><br> \
<label>Line item2:</label> \
<input type="color" name="item2" value= <%= someValue1 %>><br> \
<label>item3:</label> \
<input type="number" name="item3" min=0 value= <%= someValue2 %>><br> \
<label>item4:</label> \
<input type="color" name="item4" value= <%= someValue3 %>><br>';
// code for injecting into DOM

It's a bit more typing and breaking up, but it will solve your issue for setting the template.

If you're up for it, you can do this utilizing a small amount of PHP instead, which won't be visible to the average user (requires some serious hacking to view active PHP code if you don't have access to the server). Alter the template this way:

// code for setting item_id
var template = '<?php $selected = ' + item_id + ' ?> \
<select id ="someId" name="someName"> \
    <option <?php if($selected === 1){ echo 'selected'; } ?> >One</option> \
    <option <?php if($selected === 2){ echo 'selected'; } ?> >Two</option> \
    <option <?php if($selected === 3){ echo 'selected'; } ?> >Three</option> \
</select><br> \
<label>item1:</label> \
<input type="text" name="item1" value= <%= someValue %>><br> \
<label>Line item2:</label> \
<input type="color" name="item2" value= <%= someValue1 %>><br> \
<label>item3:</label> \
<input type="number" name="item3" min=0 value= <%= someValue2 %>><br> \
<label>item4:</label> \
<input type="color" name="item4" value= <%= someValue3 %>><br>';
// code for injecting into DOM

The first line of PHP sets the value of the variable $selected and the next 3 lines check for that value and set the correct option to selected. This is the quickest fix I know of, but it requires a PHP processing engine such as Apache. Most hosting has it enabled (at least that I've worked with).

答案 1 :(得分:0)

If I understand your question an easy way to set an option would be like this using just jQuery.

$(function(){
setOption(2);//selects third option 
});

function setOption(option){
var itter = 0;
$("select option").each(function(){
    if(itter = option)
        $(this).prop('selected', true);
});
}

Of course if you are using a template you can use a plugin like jQuery Template create an object and use it alongside your template CDN : http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js

function selectedOptions(){
    this.opt1 = "";
    this.opt2 = "selected";
    this.opt3 = "";
}
var options = new selectedOptions();
$.tmpl(yourTemplateVariable, options);

You can attach a listener to the select element and when it changes change the options object to reflect the change.

your template would need these values

<option ${opt1}>One</option>
<option ${opt2}>Two</option>
<option ${opt3}>Three</option>

I doubt this is the answer you were looking for, but maybe it can be of some help.

答案 2 :(得分:0)

This should get you started on doing things the Marionette™ way: http://codepen.io/benjarwar/pen/YyvOOx

The basic idea is, since you want some sort of synchronization between two different sets of markup with the same underlying data, Marionette is perfect for applying an MVC architecture and using the power of templates/Views to display that data in different contexts.

In my opinion, structuring your application with some sort of MVC architecture (Backbone/Marionette, Angular, React, et al) gives you much more maintainable code. Avoid falling into the trap of writing spaghetti jQuery. Learn how to create event driven JavaScript that separates concerns between a logic/controller layer and a display/view layer.

Update: I went ahead and fleshed this out a little more, adding event bindings so that when you change the selected option in the dropdown, the InputsView re-renders, highlighting the currently selected option.

HTML:

<div id="select" class="container"></div>
<div id="inputs" class="container"></div>

<script id="select-template" type="text/html">
  <select class="select-menu">
    <% _.each(items, function(option){ %>
      <option name="<%= option.name %>" <% if (option.selected) { %>selected<% } %>>
        <%= option.value %>
      </option>
    <% }); %>
  </select>
</script>

<script id="inputs-template" type="text/html">
  <% _.each(items, function(option){ %>
    <label <% if (option.selected) { %>class="selected"<% } %>><%= option.name %>:</label>
    <input type="text" name="<%= option.name %>" value="<%= option.value %>">
    <br>
  <% }); %>
</script>

CSS:

body {
  padding: 100px;
  font-family: sans-serif;
}

.container {
  margin: 20px;
}

label, input {
  margin: 5px 0;
}

.selected {
  color: red;
  font-weight: bold;
}

JS:

var data = [
  { name: "Foo", value: 'bar', selected: false },
  { name: "Baz", value: 'quz', selected: true },
  { name: "Norf", value: 'zap', selected: false }
];

// create a new Collection from the initial data
var options = new Backbone.Collection(data);

// a View for rendering the dropdown
var SelectView = Marionette.ItemView.extend({
  template: "#select-template",

  // set your ui hash
  ui: {
    "select": ".select-menu"
  },

  // fire an event when the select menu changes
  events: {
    "change @ui.select": "handleSelectChange"
  },

  handleSelectChange: function(e) {
    var $selected = $(e.target).find(":selected"),
        selectedName = $selected.attr("name"),
        selectedModel = this.collection.findWhere({ name: selectedName });

    // on select change, first deselect any previously selected Models
    this.collection.forEach(function(model, index) {
      model.set("selected", false);
    });

    // set the newly selected Model
    selectedModel.set("selected", true);
  }
});

// a View for rendering the inputs
var InputsView = Marionette.ItemView.extend({
  template: "#inputs-template",

  initialize: function() {
    this.listenTo(this.collection, "change", this.render);
  }
});

// instantiate the Views with the same Collection
var inputsView = new InputsView({collection: options});
var selectView = new SelectView({collection: options});


// create a region manager (alternatively build a Marionette.App, or use a LayoutView, etc.)
var rm = new Marionette.RegionManager();

// set up your regions
var regions = rm.addRegions({
  select: "#select",
  inputs: "#inputs"
});

// show your views
regions.select.show(selectView);
regions.inputs.show(inputsView);

JS dependencies: jQuery, Underscore, Backbone, Marionette

答案 3 :(得分:0)

我解决问题的方式真的很脏,但它有效,所以答案是

<label>Somelabel:</label>
<select name="someName" value= <%= someValue %>>
    <option value="One"<% if (someValue === "One") print("selected")%>>One</option>
    <option value="Two"<% if (someValue === "Two") print("selected")%>>Two</option>
    <option value="Three"<% if (someValue === "Three") print("selected")%>>Three</option>
</select><br>