I'm opening a new window to another .aspx page in which I pass a couple of parameters and I wanted to re-pass the parameter ID from the actual page:
<asp:Button ID="Button1" runat="server" CausesValidation="False" meta:resourceKey="btnAddRow2"
OnClientClick="window.open('SecondPage.aspx?type=Usuaris&id=SPECIALID', '_blank')" Text="Miau" />
As you can see, the type parameter works well but I don't have the slightest idea how to get the "specialID" from the current page which would be:
http://blablabla.com/FirstPage.aspx?SPECIALID=36
So i want to get that 36 (which is a dynamic number so I can't actually put a 36 directly over there) in order to open the second page as follows:
http://blablabla.com/SecondPage.aspx?type=Usuaris&SPECIALID=36
As I said at the beginning the user IS at he FirstPage.aspx and upon pressing a button will go to the SecondPage.aspx
hi you can change the OnClientClick to call a javascript function which will get the specialId and then call the window.open with the full string.
for example
function openWindow(){
var specialId = document.getElementById('someElement').value;
window.open('SecondPage.aspx?type=Usuaris&id=' + specialId, '_blank')"
}
I finally could do it doing the following in the FirstPage.aspx:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function AddUsuario() {
var id = getParameterByName("id");
window.open('SecondPage.aspx?type=Usuarios&id=' + id, '_blank');
location.reload();
}
On Page_Load() do following
Button1.Attributes.Add("onclick",
String.Format("window.open('SecondPage.aspx?type=Usuaris&id={0}', '_blank');",
Request.QueryString["SPECIALID"]));
Related
In my aspx markup I have the following defined:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="hidField" />
I have C# code as follows, which gives my hidden field a value:
hidField.value = check().ToString();
assume that check is a function which returns true, for simplicity.
I made JS code to do the following:
_myBool = $("#hidField");
alert(_myBool.value);
This alerts undefined.
For debugging purposes, I stepped through and saw that in C#, hidField.value is indeed true.
And I tried alerting _myBool.length which returned 1 and _myBool which returned [Object object] so Im not calling undefined on undefined.
Try this
_myBool = $("#hidField"); //my bool is a jQuery Object
alert(_myBool.val()); //can only get value with .val()
OR
_myBool = $("#hidField")[0]; //[0] gets the element in the object
alert(_myBool.value); //can use the javascript .value
Missing $ symbol..
var _myBool = $("#hidField");
alert(_myBool[0].value); // DOM Object
alert(_myBool.val() ); // jQuery Object
Also note the selector might Not work with runat="server" attribute as it prepends the content placeholder..
This is a better selector
var _myBool = $('[id*="hidField"]');
You forgot the dollarsign and also use the val() function
alert($("#hidField").val());
Make sure you are using the right ID:
_myBool = $("#<%= hidField.ClientID %>").val();
View your source when the page loads and check for that field. Chances are the ID is not "hidField". The code above will be correct.
Note:
To answer this question, you shouldn't have to know anything about Selenium or WebDriver, just jQuery knowledge. That's where I don't have enough knowledge--precisely why I'm asking this question. :-) If you haven't heard of Selenium WebDriver, it's just a way to automate your website or web application from code (I'm using the C# client drivers in my example).
Also note, my FirefoxDriver object has native events turned on
Environment:
Below is a snippet of HTML and JavaScript to text you type in an input field autocomplete when you start typing. When you choose a value, it sets a hidden field with the id of the value chosen based on the name of the record entered into the input field. My goal is to mimic this autocomplete behavior in WebDriver by calling the ExecuteScript method to call some jQuery code. But since I know the exact value we're trying to match on in WebDriver, I want to mimic what the end-user would type into the field with this value. How can this be done?
If I can't get this working, my answer will be to just set the hidden field directly with the id. But I'd rather pass it the text so I can actually mimic what the end-user is doing. The WebDriver script will only have some or all of the text being typed (value being set in ac_variation_id), and will not have the record id being retrieved via AJAX (value being set in variation_id hidden field). Below, I'm setting both values. However, I just want a jQuery script that gets the id and sets the id, or mimics typing the value into the input.
So I have to solve it one of two ways:
- have WebDriver mimic autocomplete 100%
- have WebDriver call a JavaScript script (jQuery AJAX call) that does everything the page does except typing the value, so that the hidden field is set with the id returned for the chosen option
I just don't know how to do either.
Example jQuery script setting hidden field with id and input field with text:
Element.SetValueById(driver, "variation_id", discount.Variation); // set input field with text
Element.SetValueById(driver, "ac_variation_id", "123"); // set hidden field with id
public static void SetValueById(IWebDriver driver, string tagId, string newValue)
{
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("$('#" + tagId + "').val('" + newValue + "')");
}
HTML code and JavaScript code for autocomplete functionality:
<link rel="stylesheet" href="http://localhost/admin/css/vanilla/jquery.ui.autocomplete.css" media="screen" type="text/css" />
<script type='text/javascript' src="http://localhost/admin/js/vanilla/jquery-ui-1.7.1.custom.min.js"></script>
<script type="text/javascript" src="http://localhost/admin/js/vanilla/jquery.ui.autocomplete.ext.js"></script>
<script type="text/javascript" src="http://localhost/admin/js/vanilla/jquery.ui.autocomplete.js"></script>
<input type="text" name="ac_variation_id" id="ac_variation_id" value="" class="autocomplete" autocomplete="off" />
<button type="button" value="clear" name="cl_variation_id" id="cl_variation_id" onclick="$('#variation_id').val('');$('#ac_variation_id').val('');" >clear</button>
<input type="hidden" name="variation_id" id="variation_id" value="" />
<script>
$('#ac_variation_id').autocomplete({
ajax: 'http://localhost/admin/discount/ajax-auto-complete/variation',
match: function(typed) {
return this.name;//.match(new RegExp("^"+typed, "i")); had to comment that out to be able to type integration_id and display name
},
insertText: function(entity) {
return entity.name +' '+ (( entity.integration_id == undefined ) ? '' : entity.integration_id);
}
}).bind("activate.autocomplete",function(e, entity){
var id = '#'+($(this).attr('id').substring(3));//remove ac_ prefix
$(id).val( entity.id );
});
</script>
Screen shot of autocomplete lookup values after typing text into the input field:
There are two things to test with the autocomplete widget: 1) typing into the text field and 2) selecting an item from the auto complete list.
These answers are in ruby, but I would suspect there is a corresponding C# version
Typing into the text field
search_term = "stackoverflow.com"
input = find('#q')
input.click
# this is the same as input.set(search_term[0..5]) I believe
search_term[0..5].chars.each do |key|
input.native.send_key(key)
end
Selecting an item from the autocomplete list (by the text of the item)
search_term = "stackoverflow.com"
selector = ".ui-menu-item a:contains(\"#{#search_term}\")"
page.execute_script " $('#{selector}').trigger(\"mouseenter\").click();"
# I have 4 auto completes on my page, so I just wait until they all gone
wait_until do
autocompletes = all(:css, '.ui-autocomplete')
autocompletes.inject(true) { |x,autocomplete| x && !autocomplete.visible? }
end
I couldn't mimic the auto-complete and selecting the option, so I'm calling the JSON GET request to get the id of the hidden field, and setting the hidden field on the match of the first that it finds (in case there are more than one).
Element.SetHiddenFieldIdViaAutoCompleteJSON(driver, "/admin/discount/ajax-auto-complete/variation", "val", discount.Variation, "id", "variation_id");
public static void SetHiddenFieldIdViaAutoCompleteJSON(IWebDriver driver, string requestPage, string queryParam, string queryParamValue, string jsonObjectProperty, string hiddenFieldId)
{
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("$.ajax({ url: '" + Config.SITE_URL + requestPage + "',data:{'" + queryParam + "':'" + queryParamValue + "'},dataType:'json',type: 'GET',contentType: 'application/json',success: function(jsonObject) { $('#" + hiddenFieldId + "').val(jsonObject[0]." + jsonObjectProperty + "); } });");
}
Using the Selenuim IDE, and exporting to Java code, I adapted the results to following function so that I can choose which of my Autocomplete Comboboxes to change. ( This also in a 'Base' class, that all my PageObjets extend.
public BasicPage selectComboBox(int buttonIndex, String selection) {
driver.findElement(By.xpath("(//button[#type='button'])[" + buttonIndex + "]")).click();
driver.findElement(By.xpath("//html/body/ul/li/a[. = \"" + selection + "\"]")).click();
// delay till the selected element is visible
WebElement duh = (new WebDriverWait(driver, 10)).until( visibilityOfElementLocated(By.xpath("(//button[#type='button'])[" + buttonIndex +"]" )) ) ;
return this;
}
I am working on a donations website. In my page, I have a textbox which accepts a numeric value from the user (that is, money to be donated).
In my code-behind, I have a method which checks whether the value in the textbox is numeric. The method generates an error message if the number is invalid.
I also have a JavaScript which, after checking that the value in the textbox is numeric, opens a new tab to the website confirmation page, thanking the user for his donation. Here is the code of the javascript:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
if (textbox.value != "")
{
if (isNan(textbox) == false)
{
window.open("DonationConfirmation.aspx")
}
}
}
</script>
The problem is that the tab is NEVER opened, even if the number is valid. Can you please help me solve this problem? Thank you.
P.S.
Here is the code of the button that initiates the validation:
<asp:ImageButton ID="PayPalButton2" runat="server" ImageAlign="Middle"
ImageUrl="Resources/Icons/PayPalCheckOut.gif"
onclick="PayPalButton2_Click" OnClientClick="Open_Window()"/>
The function name is isNaN. Note: The final 'N' is capital. That should solve your problem.
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
if (textbox.value != "" && !isNaN(textbox.value)) {
window.open("DonationConfirmation.aspx");
}
}
</script>
edit
instead of isNan should be isNaN (javascript is casesensitive)
Shouldn't this line...
if (isNan(textbox) == false)
be this instead...
if (isNan(textbox.value) == false)
First, I would recommend explicitly parsing the number, not relying on the implicit ToNumber operation that will be applied when you pass a string into isNaN. Presumably your users are inputting decimal, so if it's meant to be a whole number (e.g., 10), use:
var num = parseInt(textbox.value, 10);
If it's meant to be a number with a fractional component (e.g., 10.5), use:
var num = parseFloat(textbox.value);
You probably want parseFloat for a currency value.
Then your if condition becomes isNaN (note that the final N is capped) on num:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
var num = parseInt(textbox.value, 10);
if (!isNaN(num))
{
window.open("DonationConfirmation.aspx")
}
}
</script>
And lastly, are you sure that the client-side ID of the textbox really is 'DonationTextBox'? ASP auto-generates client-side IDs, you may need to use ClientID instead, e.g.:
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
Here is a stripped down working jsFiddle example:
http://jsfiddle.net/pjgalbraith/QZeSF/
The html:
Open
<textarea id="donationTextBox">1</textarea>
And the js:
function openWindow() {
if($('#donationTextBox').val() && isNaN($('#donationTextBox').val()) === false)
window.open("http://www.google.com/", "mywindow");
}
$(document).ready(function() {
$('#PayPalButton2').click(function(){
openWindow();
});
});
Hi i have the following pagemethod, however it dues not seem to be working, i tried debugging it and it does not hit the method. Here is what my method looks like;
function InsertStatus() {
var fStatus = document.getElementById('<%=txtStatus.ClientID %>').value;
PageMethods.InsertStatusUpdate(fStatus, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
And my codebehind;
[WebMethod]
public static string InsertStatusUpdate(string fStatus)
{
string Result = "";
int intUserID = -1;
if (String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
HttpContext.Current.Response.Redirect("/login");
else
intUserID = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
if (string.IsNullOrEmpty(fStatus))
return Result = "Please enter a status";
else
{
//send data back to database
return Result = "Done";
}
}
When i click my button it goes straight through the onError Method. Can anyone see what i am doing wrong?
I found the problem i needed a [System.Web.Script.Services.ScriptService] above the method, due to the fact it is being called by a script. Thanks for all the suggestions.
If I were to guess, I would focus on this:
intUserID = Convert.ToInt32(HttpContext.Current.User.Identity.Name);
The best way to solve this is set a breakpoint and start walking through the code. When you run a line and are redirected to the error page, you have found your problem.
The reason I picked that line, is the user is a string. Now, it may be your users are numbers, but it could also be including a domain user == "mydomain/12345", which is not an integer, even if the user part of the string is.
As far as I know, you can't Response.Redirect in a PageMethod.
Return a string of the redirect URL and then use JavaScript document.location.href to handle the redirection.
EDIT: I've just seen that you tried debugging and the method isn't hit: ensure your ScriptManager has EnablePageMethods set to true:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
i have made a session variable Session["Background1"] = value; in one of my code behind function i want to retrieve this value in my javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
Personally, I prefer to do it the scripting way. Suppose your variable is currently declared in your Javascript as:
var background1 = null; // TODO: Add value from session.
To add the value from session, all you need to do is this:
var background1 = '<%= Session["Background1"] %>';
When the page is output by ASP.NET, the expression between <%= and %> is evaluated and written to the page, effectively becoming a Response.Write. As long as the member is available in your page at the public or protected level, you can push it into your Javascript it in this way.
I find this approach easier to work with than the obnoxiously verbose ClientScriptManager.