Selecting a dropdown option from webbrowser - c#

My goal I need to select the second option.
I've tried following approach and can't set selected value. No error shows up, the selection just doesn't happen. Being very familiar with HTML myself, I know that "selected" and 'selected="selected"' work but not sure why it's not working with my C# code. What could be wrong?
webBrowser1.Document.GetElementById("field_gender1").
Children[1].SetAttribute("selected", "selected");
The HTML is
<select name="gender1" id="field_gender1" class="select">
<option selected="selected" value="1">val1</option>
<option value="2">val2</option>
</select>

Do this from WebBrowser_DocumentComplete(...)
var htmlDocument = webBrowser1.Document as IHTMLDocument2;
if (htmlDocument != null)
{
var dropdown = ((IHTMLElement)htmlDocument.all.item("field_gender1"));
var dropdownItems = (IHTMLElementCollection)dropdown.children;
foreach(IHTMLElement option in dropdownItems)
{
var value = option.getAttribute("value").ToString();
if(value.Equals("2"))
option.setAttribute("selected", "selected");
}
}

Your code should be working if it's at a suitable place, eg: button1_Click event, webBrowser1_DocumentCompleted event, etc.

Related

How can I determine selected value in dropdown without using bind in Blazor?

I'm trying to do this all in C# but I may have to resort to JavaScript.
I have a dropdown that I want to do an onchange event. I can't bind the dropdown to the model as binding prevents the use of onchange. I need to use the onchange event to modify some things on the screen depending on what is selected. Maybe some code will help.
<select id="BrandSelected" #onchange="BrandIsChanged">
<option value="NewBrand">--Create New Brand--</option>
#foreach (var brand in Brands)
{
if(Model.BrandID == brand.BrandID)
{
<option value="#brand.BrandID" selected>#brand.Brand</option>
}
else
{
<option value="#brand.BrandID">#brand.Brand</option>
}
}
</select>
<label id="BrandLabel" hidden>New Brand</label>
<InputText id="NewBrandInput" #bind="NewBrandProp" hidden></InputText>
So I'm adding the option at the top to create a new brand. This is an upsert so it's possible one of the brands may already be selected. It will still be changeable on update. It works if the user selects any of the existing brands but I want to be able to add a new brand if it does not exist in the dropdown. If in the BrandIsChanged method, the NewBrand has been selected, then I want to create a new brand with the value in the InputText. This means I will have to modify both the label and the InputText to be visible onchange if the selected value is NewBrand. So, how can I determine in the BrandIsChanged method what the selected item (BrandSelected) value is?
Other things that might be helpful:
#code{
//Populated on load in a method
private IEnumerable<T_IFS_BrandDTO> Brands { get; set; } = new List<T_IFS_BrandDTO>();
//The new brand, if user decides to enter one.
private string NewBrandProp { get; set; }
}
The onchange event passes ChangeEventArgs parameter to your event handler which you can use to get the selected value.
<select id="BrandSelected" #onchange="BrandIsChanged">
...
</select>
#code {
private BrandIsChanged(ChangeEventArgs args)
{
if (args?.Value?.ToString() == "NewBrand")
{
// do stuff
}
}
}

DropDownListFor onchange but for same value

I'm trying to trigger an onchange event, even if the value they select is the same as before. I have tried onselect, but it does not trigger at all. And onchange does not trigger if value is the same. Is there any other patterns I could use to make this possible?
#Html.DropDownListFor(m => m.SelectedMarkdownDate, Model.ValidDatesSelectList, new{onchange = "LoadGridData(this);" })
Ended up using JQuery:
var go = false;
$('#SelectedMarkdownDate').on('click',function() {//on click
if (go) {//if go
var date = $('#SelectedMarkdownDate option:selected').text();
LoadGridData(date);
go = false;//switch off
} else { go = true; }//if !go, switch on
}).on('blur', function () { go = false; });
It looks like you answered your question, however I already made a fiddle so here it is.
you can use the onClick event with blur to tell whether or not the dropdown is open, when you select the same item it gives you an alert just to demonstrate that it recognizes the event.
https://jsfiddle.net/Anon_E_Mustard/yoxs0gk8/
<script>
var dropboxOpen = false,
oldItem = null;
counter = 0;
function onClick(e) {
if (dropboxOpen) {
if (oldItem && oldItem === e.target.value) {
alert("same selected")
}
oldItem = e.target.value;
dropboxOpen = false;
}else{
dropboxOpen = true;
}
}
function onBlur(e){
dropboxOpen = false;
}
</script>
<select onclick="onClick(event)" onblur="onBlur(event)">
<option value="volvo">volvo</option>
<option value="saab">saab</option>
<option value="opel">opel</option>
<option value="audi">audi</option>
</select>

validation for drop down select in mvc

In MVC form I have a drop down list which has 3 hard coded options.
<select name="ComparisonType">
<option>select ..</option>
<option>Life</option>
<option>Income</option>
</select>
On form submit values will be saved but there need to add validation for First option. If user submit form he should see message.
Please advice how to handle it. I'm not using Model here.
Modify your html as shown:
<select name="ComparisonType">
<option value="0">select ..</option>
<option value="Life">Life</option>
<option value="Income">Income</option>
</select>
Jquery :
$('form').submit(function(e){
if($('select[name=ComparisonType]').val() == "0")
{
alert("Please select any value from dropdown");
e.preventDefault(); //or return false;
}
});
Edit :-
DEMO Link
You will have to use Javascript/Jquery to achieve this functionality as you are not using a model here. So you can work around with this code which will validate your dropdown on submitting your form. Here goes :
<script type="text/javascript">
$(document).ready(function () {
$('#submitButtonId').click(function (){
var period = $("#dropdownId option:selected").text();
if (period == "select") {
//means first option is selected.
}
else {
//some other option is selected.
}
});
});

javascript enable textbox on dropdown change event

i have five dropdown and five texbox and I'm checking on click of any of the dropdown the corresponding texbox should get enabled/disabled through javascript am using master page in asp.net
e.g: if am selecting dropdownlist1 then texbox1 should get enabled,for one textbox its working how to make it work for five textbox
function HideTextBox(ddlId) {
var ControlName = document.getElementById(ddlId.id);
if (ControlName.value == 0)
{
document.getElementById('<%=txtComment1.ClientID%>').disabled = true;
}
else {
document.getElementById('<%=txtComment1.ClientID%>').disabled = false;
}
}
You can use JQuery, it is better way. Set two class to each textBox, first .textBox1 .myTexts,
the first class must include an id for text boxes. Such as .textBox1, .textBox2 ect. And your dropbox value must include just text box's id.
$(document).ready(function(){
$("#dropBoxID").change(function(){
$(".myTexts").attr('disabled','disabled');
$(".textBox"+$(this).val()).removeAttr("disabled")
});
});
try this
http://jsfiddle.net/3WJtM/
function HideTextBox(ddlId) {
var ControlName = document.getElementById(ddlId.getAttribute("id"));
var idTxt = ControlName.getAttribute("txt");
if (ControlName.value == 0)
{
document.getElementById(idTxt).disabled = true;
}
else {
document.getElementById(idTxt).disabled = false;
}
}
on every object select, add an attribute txt with the name of te input text
In the javascript you search this textbox for enabled or disabled
for example
<select id="ddl1" txt="txt1" onchange="HideTextBox(this);" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="input" id="txt1" disabled/>

Passing id and finding the element in javascript

I'm extremely new to JavaScript and am stumped on this one. I'm trying to send the ClientID of a Control to a js function. The function should then find the element and get the Control's value. To note: I am using a master page, and the Control I am passing the ClientID of is in a UserControl.
ASP:
//code here
<asp:TableCell runat="server">
<asp:DropDownList runat="server" ID="variableDDL"/>
//some ListItems
</asp:Tablecell>
//more cells here
<asp:TableCell runat="server">
<asp:ImageButton runat="server" ID="iButton" ImageUrl="~/Images/iButton.png" OnClientClick="iButtonClick(<%=variableDDL.ClientID%>);"/>
</asp:TableCell>
//code here
.js:
function iButtonClick(ClientID)
{
var v = document.getElementById(ClientID);
var val = v.value;
alert(val);
}
Every time I click the button, nothing happens. Changing the sent parameter to <%#variableDDL.ClientID%> does the same thing. Changing it to '<%=variableDDL.ClientID%>' or '<%#variableDDL.ClientID%>' gives a null pointer error since it can't find the object. The script is referenced correctly, and does fire if I change it to not accept a parameter and just produce an alert. Anyone know what I'm doing wrong?
EDIT: The requested code is shown below.
ASP UserControl:
protected void Page_Init(object sender, EventArgs e) {
DataTable fields = (DataTable) Session["fields"];
for(int i = 0; i < fields.Rows.Count; i++)
{
variableDDL.Items.Add(new ListItem(fields.Rows[i]["Field"].ToString(), fields.Rows[i]["Field"].ToString();
}
}
Rendered OnClick HTML:
'<%=variableDDL.ClientID%>' produces
onclick="iButtonClick('<%=variableDDL.ClientID%>');"
<%=variableDDL.ClientID%> produces
onclick="iButtonClick(<%=variableDDL.ClientID%>);"
'<%#variableDDL.ClientID%>' produces
onclick="iButtonClick('<%#variableDDL.ClientID%>');"
<%#variableDDL.ClientID%> produces
onclick="iButtonClick(<%#variableDDL.ClientID%>);"
By the look of it,
OnClientClick="iButtonClick(<%=variableDDL.ClientID%>);"
is getting rendered literally - it's not replacing the contents of the angle brackets.
Try
OnClientClick='iButtonClick("<%=variableDDL.ClientID%>");'
Note the single quotes for the property - I think this does make a difference - and the double quotes so the result becomes a JavaScript string literal.
If this doesn't work, you might have to set
iButton.OnClientClick = "iButtonClick('" + variableDDl.ClientID + "');";
in an event in your codebehind.
If you are not against jQuery, you could easily perform this operation by adding an identifying class to your select element, since it gets a unique client id.
<select id="variableDDL" class='varddl'>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button id="btn1" type="button">Click here</click>
$("#btn1").click(function(e){
var v = $(".varddl:first-child").val();
alert('Value of '+ $(".varddl:first-child").attr('id') + 'is ' + v);
});
Click here to view the fiddle
UPDATE: Pure JS Version
function btnClick(e){
//Select the first occurance, [0]
var ele = document.getElementsByClassName('varddl')[0];
if(ele){
//There's the value
var val = ele.value;
alert(val);
}
}
var btn1 = document.getElementById("btn1");
btn1.onclick = btnClick
;
Here is the JS Only Fiddle
This is how ASP.Net works: you cannot use servercode (<%%>) inside ASP.Net WebControls.
You can solve this by putting the ClientID directly in the javascript code:
function iButtonClick()
{
var v = document.getElementById('<%= variableDDL.ClientID %>');
var val = v.value;
alert(val);
}
You can also pass an object directly in the OnClientClick, with the restriction that you can only send the object itself:
OnClientClick="ButtonClick(this);"

Categories

Resources