How to Dynamically Assign DropDown Value in MVC 5 View - asp.net-mvc

I have a Model that contains basic address information:
public class AddressModel()
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
When passing it into a form in my View, I am placing the values into a textbox, except for the State, which is a dropdown box that is hardcoded to contain the states in America:
<form>
<div class="container-fluid">
<div class="col-md-3">
<div class="form-group">
<!-- First Name -->
<label for="first_name_id" class="control-label">First Name</label>
<input type="text" class="form-control" id="first_name_id" name="first_name" placeholder="First Name" value="#Html.ViewData.Model.Patient.FirstName.First().ToString().ToUpper()#Html.ViewData.Model.FirstName.Substring(1).ToLower()">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<!-- Last Name -->
<label for="last_name_id" class="control-label">Last Name</label>
<input type="text" class="form-control" id="last_name_id" name="last_name" placeholder="Last Name" value="#Html.ViewData.Model.Patient.LastName.First().ToString().ToUpper()#Html.ViewData.Model.LastName.Substring(1).ToLower()">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<!-- Street 1 -->
<label for="street1_id" class="control-label">Street Address 1</label>
<input type="text" class="form-control" id="street1_id" name="street1" placeholder="" value="#Html.ViewData.Patient.BillingAddress1">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<!-- Street 2 -->
<label for="street2_id" class="control-label">Street Address 2</label>
<input style="margin-left: 0px" type="text" class="form-control" id="street2_id" name="street2" placeholder="Apartment, Suite, etc." value="#Html.ViewData.Patient.BillingAddress2">
</div>
</div>
</div>
<div class="container-fluid">
<div class="col-md-4">
<div class="form-group">
<!-- City-->
<label for="city_id" class="control-label">City</label>
<input type="text" class="form-control" id="city_id" name="city" placeholder="" value="#Html.ViewData.Model.BillingCity">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<!-- State Dropdown-->
<label for="state_id" class="control-label">State</label>
<select class="form-control" id="state_id">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<!-- Zip Code-->
<label for="zip_id" class="control-label">Zip Code</label>
<input type="text" class="form-control" id="zip_id" name="zip" placeholder="" value="#Html.ViewData.Model.BillingZip">
</div>
</div>
</div>
</form>
Is there a way to assign the value/option of the drop down in this current format? I can't seem to figure out a way to set the value this way. Do I use the HTML Helper Method for dropdowns, given the list of states? Currently the Value is always set to Alabama.

Each Option element has a "Selected" property, like
<option value="CA" selected="selected">California</option>
You could also set in javascript like
document.getElementById("state_id").value = "CA";
I am not sure what dictates what the default value needs to be. Is there an event, like changing the text in another textbox, or a value available, like a CustomerID, that determines which Option element should be defaulted? Let me know...

Related

my tag helper Drop Down Select Will Not render properly in .NET core

<div class="form-group">
<label asp-for="roles" class="control-label"></label>
<select asp-for="roles" class="custom-select" asp-items="#(new Select List(ViewBag.Roles))">
<option value="">Assign Role</option>
</select>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select asp-for="roles" class="form-control custom-select" style="height:20px" asp-items="#(new Select List(ViewBag.Roles,"Id","Name"))">
<option value="">Large select</option>
</select>
</div>
</div>
my drop down in not responsive any help
how to make drop down responsive
It is possible that the value of ViewBag.Roles is assigned incorrectly. Here is an example.
In Index.cshtml
#{
ViewBag.Roles = new List<MyModel>
{
new MyModel{Id=1, Name="thisname"},
new MyModel{Id=2, Name="thisname2"},
};
}
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select asp-for="roles" class="form-control custom-select" style="height:20px"
asp-items="#(new SelectList(ViewBag.Roles,"Id","Name"))">
<option value="">Large select</option>
</select>
</div>
Here is the model.
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Result.

Cloning div in angular 2 the select 2 is not working properly

I am using Angular's 2 Reactive forms "Form Array's property" to make a copy of elements in a div on '+' button click, and remove that div form '-'. Button cloning is working fine but when I clone, it destroys the select 2 and select 2 is not cloning in its original form.
Here is the Component Code:
import { Component, OnChanges, AfterViewInit } from '#angular/core';
import { FormArray, FormBuilder, FormGroup} from '#angular/forms';
import { ProductPrice, OrderProduct } from './product-price-model';
declare var $:any;
#Component({
selector: 'app-order-product',
templateUrl: './order-product.component.html',
styleUrls: ['./order-product.component.css']
})
export class OrderProductComponent implements OnChanges,AfterViewInit {
myNav = 'Home';
secondNav = 'Product';
thirdNav = 'Order Products';
isThird = 'true';
OrderProductForm: FormGroup;
OrderProd : OrderProduct;
ngOnInit() {
}
ngAfterViewInit() {
$('.select-search').select2();
}
constructor(private fb: FormBuilder){
this.createForm();
}
createForm() {
this.OrderProductForm = this.fb.group({
// Vendor: '',
// OrderDateTime: '',
// DeliveryDate: '',
productPriceDiv: this.fb.array([]),
});
this.productPriceDiv.push(this.fb.group(new ProductPrice()));
}
ngOnChanges(){
this.setProductPrice(this.OrderProd.ProPrice);
alert("asd");
}
get productPriceDiv(): FormArray {
return this.OrderProductForm.get('productPriceDiv') as FormArray;
};
setProductPrice(ProdPrice: ProductPrice[]) {
const PpFGs = ProdPrice.map(product_price => this.fb.group(product_price));
const PpFormArray = this.fb.array(PpFGs);
this.OrderProductForm.setControl('productPriceDiv', PpFormArray);
}
addProductPriceDiv() {
this.productPriceDiv.push(this.fb.group(new ProductPrice()));
}
removeProductPriceDiv(index) {
this.productPriceDiv.controls.splice(index, 1);
}
}
Here is the HTML:
<form [formGroup]="OrderProductForm" (ngSubmit)="onSubmit()">
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<fieldset class="text-semibold">
<legend><i class="icon-reading position-left"></i> General</legend>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Select Vendor </label>
<select class="select-search">
<optgroup label="Mountain Time Zone">
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="WY">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone">
<option value="AL">Alabama</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
</optgroup>
<optgroup label="Eastern Time Zone">
<option value="CT">Connecticut</option>
<option value="FL">Florida</option>
<option value="MA">Massachusetts</option>
<option value="WV">West Virginia</option>
</optgroup>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Order DateTime</label>
<div class="input-group">
<span class="input-group-addon"><i class="icon-calendar3"></i></span>
<input type="text" class="form-control" id="anytime-both" value="June 4th 08:47">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Delivery Date</label>
<div class="input-group">
<span class="input-group-addon"><i class="icon-calendar22"></i></span>
<input type="text" class="form-control daterange-single" value="03/18/2013">
</div>
</div>
</div>
</div>
</fieldset>
</div>
<div formArrayName="productPriceDiv" class="col-md-12">
<fieldset>
<legend class="text-semibold"><i class="icon-truck position-left"></i> Product details</legend>
<div *ngFor="let product_price of productPriceDiv.controls; let i=index" [formGroupName]="i" class="row">
<div class="col-md-4">
<div class="form-group">
<label>Product</label>
<select class="select-search" formControlName="Product">
<optgroup label="Mountain Time Zone">
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="WY">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone">
<option value="AL">Alabama</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
</optgroup>
<optgroup label="Eastern Time Zone">
<option value="CT">Connecticut</option>
<option value="FL">Florida</option>
<option value="MA">Massachusetts</option>
<option value="WV">West Virginia</option>
</optgroup>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Unit Cost</label>
<input type="text" class="form-control" formControlName="UnitCost" readonly>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Quantity</label>
<input type="text" class="form-control" formControlName="Quantity" >
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Cost:</label>
<input type="text" class="form-control" formControlName="Cost" >
</div>
</div>
<div class="col-md-2">
<label></label>
<div class="form-group">
<button type="button" (click)="addProductPriceDiv()" class="btn border-success text-success btn-flat btn-rounded btn-icon btn-xs"><i class="icon-add" ></i></button>
<button type="button" (click)="removeProductPriceDiv(i)" class="btn border-success text-success btn-flat btn-rounded btn-icon btn-xs"><i class="icon-dash" ></i></button>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">Submit form <i class="icon-arrow-right14 position-right"></i></button>
</div>
</div>
</form>
Try methods in this way, hope your problem get solved
addProductPrice() {
return this._fb.group({
Product: [''],
UnitCost: [''],
Quantity: [''],
Cost: ['']
});
};
createForm() {
this.OrderProductForm = this._fb.group({
ProductPrice: this._fb.array([
this.addProductPrice()
])
});
}
addProductPriceDiv() {
const control = <FormArray>this.OrderProductForm.controls['productPriceDiv'];
control.push(this.addProductPrice());
}
removeProductPriceDiv(index) {
const control = <FormArray>this.OrderProductForm.controls['productPriceDiv'];
control.removeAt(index);
};

Getting extra data while using append on Jquery Mobile

I have 2 dives with some kind of form that I want to be display.
For some reason When I am using append I am getting more text that I didn't ask for.
Here is the html-
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>טריקו קצר</h3>
<div dir="rtl" data-role="fieldcontain">
<label for="select-choice-1" class="select">בחר צבע:</label>
<select name="select-choice-1" id="select-choice-1">
<option value="standard">בחר</option>
<option value="לבן">לבן</option>
<option value="שחור">שחור</option>
<option value="כחול-ים">כחול-ים</option>
<option value="בורדו">בורדו</option>
<option value="ירוק">ירוק</option>
<option value="סגול כהה">סגול כהה</option>
<option value="אדום">אדום</option>
</select>
</div>
<div dir="rtl" data-role="fieldcontain">
<label for="select-choice-2" class="select">בחר מידה:</label>
<select name="select-choice-2" id="select-choice-2">
<option class="center-button"value="standard">בחר</option>
<option value="Small">S</option>
<option value="Medium">M</option>
<option value="Large">L</option>
<option value="EE">EE</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="slider" class="select">כמות:</label>
<input type="range" name="slider" id="slider" value="0" min="0" max="500" data-highlight="true" />
<div class="ui-block-a button-basket"><button data-theme="b" id="triko" class="basket">הוסף לסל</button></div>
</div>
</div>
<!-- end TRIKO -->
<!-- ---------------------------------- GUFIOT ---------------------------------------- -->
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>גופיות קייציות</h3>
<div dir="rtl" data-role="fieldcontain">
<label for="select-choice-3" class="select">בחר צבע:</label>
<select name="select-choice-3" id="select-choice-3">
<option value="standard">בחר</option>
<option value="לבן">לבן</option>
<option value="אפור אמריקאי">אפור אמריקאי</option>
<option value="שחור">שחור</option>
<option value="כחול-ים">כחול-ים</option>
<option value="בורדו">בורדו</option>
<option value="ירוק">ירוק</option>
<option value="סגול כהה">סגול כהה</option>
<option value="אדום">אדום</option>
<option value="כחול כהה">כחול כהה</option>
<option value="ירוק כהה">ירוק כהה</option>
<option value="טורקיז">טורקיז</option>
<option value="כתום">כתום</option>
<option value="צהוב">צהוב</option>
<option value="לילך">לילך</option>
<option value="חציל">חציל</option>
<option value="ורוד">ורוד</option>
<option value="תכלת">תכלת</option>
<option value="ירוק זית">ירוק זית</option>
<option value="אופוויט">אופוויט</option>
<option value="ורוד זועק">ורוד זועק</option>
<option value="חום">חום</option>
<option value="מג'ב / לוטר">מג"ב/לוטר</option>
<option value="צהוב בננה">צהוב בננה</option>
<option value="ירוק תפוח">ירוק תפוח</option>
</select>
</div>
<div dir="rtl" data-role="fieldcontain">
<label for="select-choice-4" class="select">בחר מידה:</label>
<select name="select-choice-4" id="select-choice-4">
<option class="center-button"value="standard">בחר</option>
<option value="Small">S</option>
<option value="Medium">M</option>
<option value="Large">L</option>
<option value="EE">EE</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="slider" class="select">כמות:</label>
<input type="range" name="slider" id="slider1" value="0" min="0" max="500" data-highlight="true" />
<div class="ui-block-a button-basket"><button data-theme="b" id="gufiot" class="basket">הוסף לסל</button></div>
</div>
</div>
<div class="order">
<h3>פרטי ההזמנה</h3>
<p class="item_name"></p>
</div>
<!-- end gofiot -->
Here is my JQ code-
$(document).ready(function(){
$('#slider').on('slidestop',function(){
var changeVar = $('#slider').val();
$(".ui-block-a").one('click',function(){
$(".item_name").append("<h2>טריקו קצר</h2>" + "צבע:" + $("#select-choice-1").val() + ", כמות: " + changeVar + ", מידה: " + $("#select-choice-2").val() + "<br>")
$("#select-choice-1").val("standard")
$('#select-choice-1').selectmenu('refresh')
$("#select-choice-2").val("standard")
$('#select-choice-2').selectmenu('refresh')
$("#slider").val(0).slider("refresh");
//$( "#select-choice-1 option:selected" ).text("fffff");
});
});
$('#slider1').on('slidestop',function(){
var changeVar1 = $('#slider1').val();
$("#gufiot").one('click',function(){
$(".item_name").append("<h2>גופיות קייציות</h2>" + "צבע:" + $("#select-choice-3").val() + ", כמות: " + changeVar1 + ", מידה: " + $("#select-choice-4").val() + "<br>")
$("#select-choice-3").val("standard")
$('#select-choice-3').selectmenu('refresh')
$("#select-choice-4").val("standard")
$('#select-choice-4').selectmenu('refresh')
$("#slider1").val(0).slider("refresh");
//$( "#select-choice-1 option:selected" ).text("fffff");
});
});
If I use the first function and then use the second I am getting another line that I didn't ask for. So insted of getting -
טריקו קצר
צבע:אפור אמריקאי, כמות: 308, מידה: Small
גופיות קייציות
צבע:שחור, כמות: 318, מידה: Small
טריקו קצר
I am getting -
טריקו קצר
צבע:אפור אמריקאי, כמות: 308, מידה: Small
גופיות קייציות
צבע:שחור, כמות: 318, מידה: Small
טריקו קצר
צבע:standard, כמות: 308, מידה: standard .
If I use just 1 of the functions its all good...
Solved my own problem!
It happand because ".ui-block-a" is located on the other form so I am getting 2 appends...

Dependent drop down in jquery mobile not working

I am creating a dependent drop down list of states & city in jquery mobile. which is not working for me. I am unable to hide the 2nd drop down too. The code i am using is:
The html:
<select name="selectmenu5" id="selectmenu5">
<option value="0">Select State</option>
<option value="1">Andaman and Nicobar</option>
<option value="2">Andhra Pradesh</option>
</select>
<select name="selectmenu4" id="selectmenu4">
<option class="city" id="1">Select City</option>
<option class="city" id="2">option 2</option>
<option class="city" id="3">Option 3</option>
</select>
and the js:
$(document).ready(function() {
$("#selectmenu4").hide();
$("#selectmenu5").live("change",function() {
$("#selectmenu4").show();
switch($("#this").val()){
case "1":
$(".city").hide().parent().find("#1").show();
break;
case "2":
$(".city").hide().parent().find("#2").show();
break;
}
});
});
Is this what you want? jsFiddle: http://jsfiddle.net/WXbbj/40/
Create all the selects:
<select name="selectmenu5" id="selectmenu5">
<option value="0">Select State</option>
<option value="1">Andaman and Nicobar</option>
<option value="2">Andhra Pradesh</option>
<select class='cityList' name="selectmenu1" id="selectmenu1">
<option class="city" id="0">Select City</option>
<option class="city" id="1">city1</option>
<option class="city" id="2">city2</option>
</select>
<select class='cityList' id="selectmenu2">
<option class="city" id="0">Select City</option>
<option class="city" id="1">city3</option>
<option class="city" id="2">city4</option>
</select>
Basically i use css to hide the "selectmenu" :
#selectmenu1,#selectmenu2{
display:none;
}
And this is the jquery function to show only the right options:
$(document).ready(function() {
$("#selectmenu5").on("change",function() {
$(".cityList").hide();
$("#selectmenu"+$(this).val()).show();
}); });

change jquery mobile color swatch dynamically

I want to change a jquery-mobile buttons color swatch dynamically with javascript, but I can't' find a way (except removing and adding all classes and event handlers, but that's to messy).
Whats the best way to do that?
At least in 1.2.0 (1.2.0-rc1) its as simple as (probably it works in minor versions):
$( "#myButton" ).buttonMarkup({theme: 'd'});
not .button('refresh') needed
Well I did do something like this:
http://jsfiddle.net/Sgrve/20/
http://jsfiddle.net/Sgrve/28/ (All form elements)
JS (might need minor tweaks to get what you want)
$('input[name=theme-options]').change(function() {
var currentTheme = $('#home').attr('data-theme');
var selectedTheme = $(this).val();
alert('CT '+currentTheme+' ST '+selectedTheme);
$('.ui-body-' + currentTheme).each(function(){
$(this).removeClass('ui-body-' + currentTheme).addClass('ui-body-' + selectedTheme);
});
$('.ui-btn-up-' + currentTheme).each(function(){
$(this).removeClass('ui-btn-up-' + currentTheme).addClass('ui-btn-up-' + selectedTheme);
});
$('.ui-btn-down-' + currentTheme).each(function(){
$(this).removeClass('ui-btn-down-' + currentTheme).addClass('ui-btn-down-' + selectedTheme);
});
$('#home').find('*[data-theme]').each(function(index){
$(this).attr('data-theme',selectedTheme);
});
$('#home').attr('data-theme', selectedTheme).removeClass('ui-body-' + currentTheme).addClass('ui-body-' + selectedTheme).trigger('create');
});
HTML (might need minor tweaks to get what you want)
<div data-role="page" id="home" data-theme="a">
<div data-role="content">
<div class="content-primary">
<p>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose a Theme:</legend>
<input type="radio" name="theme-options" id="theme-option-a" value="a" checked="checked" data-theme="a" />
<label for="theme-option-a" data-theme="a">Theme A</label>
<input type="radio" name="theme-options" id="theme-option-b" value="b" data-theme="b" />
<label for="theme-option-b" data-theme="b">Theme B</label>
<input type="radio" name="theme-options" id="theme-option-c" value="c" data-theme="c" />
<label for="theme-option-c" data-theme="c">Theme C</label>
<input type="radio" name="theme-options" id="theme-option-d" value="d" data-theme="d" />
<label for="theme-option-d" data-theme="d">Theme D</label>
<input type="radio" name="theme-options" id="theme-option-e" value="e" data-theme="e" />
<label for="theme-option-e" data-theme="e">Theme E</label>
</fieldset>
</div>
</p>
<form action="#" method="get">
<h2>Form elements</h2>
<div data-role="fieldcontain">
<label for="name">Text Input:</label>
<input type="text" name="name" id="name" value="" />
</div>
<div data-role="fieldcontain">
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
</div>
<div data-role="fieldcontain">
<label for="search">Search Input:</label>
<input type="search" name="password" id="search" value="" />
</div>
<div data-role="fieldcontain">
<label for="slider2">Flip switch:</label>
<select name="slider2" id="slider2" data-role="slider">
<option value="off">Off</option>
<option value="on">On</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="slider">Slider:</label>
<input type="range" name="slider" id="slider" value="0" min="0" max="100" />
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose as many snacks as you'd like:</legend>
<input type="checkbox" name="checkbox-1a" id="checkbox-1a" class="custom" />
<label for="checkbox-1a">Cheetos</label>
<input type="checkbox" name="checkbox-2a" id="checkbox-2a" class="custom" />
<label for="checkbox-2a">Doritos</label>
<input type="checkbox" name="checkbox-3a" id="checkbox-3a" class="custom" />
<label for="checkbox-3a">Fritos</label>
<input type="checkbox" name="checkbox-4a" id="checkbox-4a" class="custom" />
<label for="checkbox-4a">Sun Chips</label>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Font styling:</legend>
<input type="checkbox" name="checkbox-6" id="checkbox-6" class="custom" />
<label for="checkbox-6">b</label>
<input type="checkbox" name="checkbox-7" id="checkbox-7" class="custom" />
<label for="checkbox-7"><em>i</em></label>
<input type="checkbox" name="checkbox-8" id="checkbox-8" class="custom" />
<label for="checkbox-8">u</label>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Layout view:</legend>
<input type="radio" name="radio-choice-b" id="radio-choice-c" value="on" checked="checked" />
<label for="radio-choice-c">List</label>
<input type="radio" name="radio-choice-b" id="radio-choice-d" value="off" />
<label for="radio-choice-d">Grid</label>
<input type="radio" name="radio-choice-b" id="radio-choice-e" value="other" />
<label for="radio-choice-e">Gallery</label>
</fieldset>
</div>
<div data-role="fieldcontain">
<label for="select-choice-1" class="select">Choose shipping method:</label>
<select name="select-choice-1" id="select-choice-1">
<option value="standard">Standard: 7 day</option>
<option value="rush">Rush: 3 days</option>
<option value="express">Express: next day</option>
<option value="overnight">Overnight</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="select-choice-3" class="select">Your state:</label>
<select name="select-choice-3" id="select-choice-3">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="select-choice-a" class="select">Choose shipping method:</label>
<select name="select-choice-a" id="select-choice-a" data-native-menu="false">
<option>Custom menu example</option>
<option value="standard">Standard: 7 day</option>
<option value="rush">Rush: 3 days</option>
<option value="express">Express: next day</option>
<option value="overnight">Overnight</option>
</select>
</div>
<div class="ui-body ui-body-b">
<fieldset class="ui-grid-a">
<div class="ui-block-a"><button type="submit" data-theme="d">Cancel</button></div>
<div class="ui-block-b"><button type="submit" data-theme="a">Submit</button></div>
</fieldset>
</div>
</form>
</div><!--/content-primary -->
<div class="content-secondary">
<div data-role="collapsible" data-collapsed="true" data-theme="b">
<h3>More in this section</h3>
<ul data-role="listview" data-theme="c" data-dividertheme="d">
<li data-role="list-divider">Form elements</li>
<li>Form basics</li>
<li data-theme="a">Form element gallery</li>
<li>Text inputs</li>
<li>Search inputs</li>
<li>Slider</li>
<li>Flip toggle switch</li>
<li>Radio buttons</li>
<li>Checkboxes</li>
<li>Select menus</li>
<li>Theming forms</li>
<li>Native form elements</li>
<li>Submitting forms</li>
<li>Plugin methods</li>
</ul>
</div>
</div>
</div>
</div>
What worked for me is:
//set button active
$(this).parent().addClass('ui-btn-active');
//set button inactive
$(this).parent().removeClass('ui-btn-active');
Adding the class 'ui-btn-active' to the parent will set the current button to active and change the data-theme to 'b'. This will not work for any arbitrary swatch though. So you may still need one of the longer solutions mentioned earlier.
Yes, looks like there is no way to simply change the theme swatch.
I hacked a simple function to exchange the color by regex:
$.fn.changeColorSwatch = function(theme, type) {
if (!type) {
type = 'theme';
}
var currentTheme = this.attr('data-' + type);
if (!currentTheme) {
currentTheme = 'c';
}
this.attr('data-' + type, theme);
var regex = new RegExp('^ui-(.*)-' + currentTheme + '$');
var classes = $.extend({}, this[0].classList);
var i = classes.length;
while (i--) {
var match = classes[i].match(regex);
if (match) {
this.removeClass(match[0]);
this.addClass('ui-' + match[1] + '-' + theme);
}
}
};
I know, it should use jqmData instead of attr, but the data-theme attribute wasn't changed properly.
Buttons need to have the parent element theme changed as well.
Add the following code to the end of the $.fn.changeColorSwatch function
if(this.attr('type') == 'button'){
this.parent().changeColorSwatch(theme, type);
}
If the button is defined as:
<button type="button" id="yourbutton">Hello</button>
Then this works the fastest:
$('#yourbutton').parent().find('.ui-btn-inner').css("background-color",yournewcolor);
I use this and it works perfectly !! :D
Mikael Kindborg answer from Change data-theme in jQuery mobile
$.mobile.changeGlobalTheme = function(theme)
{
// These themes will be cleared, add more
// swatch letters as needed.
var themes = " a b c d e";
// Updates the theme for all elements that match the
// CSS selector with the specified theme class.
function setTheme(cssSelector, themeClass, theme)
{
$(cssSelector)
.removeClass(themes.split(" ").join(" " + themeClass + "-"))
.addClass(themeClass + "-" + theme)
.attr("data-theme", theme);
}
// Add more selectors/theme classes as needed.
setTheme(".ui-mobile-viewport", "ui-overlay", theme);
setTheme("[data-role='page']", "ui-page-theme", theme);
setTheme("[data-role='header']", "ui-bar", theme);
setTheme("[data-role='listview'] > li", "ui-bar", theme);
setTheme(".ui-btn", "ui-btn-up", theme);
setTheme(".ui-btn", "ui-btn-hover", theme);
};

Resources