Search keywords with enter key - BUG - javascript

So, i'm developing a search feature in my website, and i want to redirect the user to a page with the keywords he is trying to search.
The following code works, but there is a bug: when i click enter in my homepage it works. The user is successfully redirected to my search page with the results. But when i'm in that page (or any other page) the enter key does not work! Only the button works all the time! It's a strange error and i dont know what to do...
This code is in my masterpage (.net 4.0) and it is the parent of all my webforms (including home). Can anyone help me?
<asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>
<button id="BTPesquisa" class="button-search" type="button" onClick="javascript:window.location.assign('/Pesquisa?val='+encodeURIComponent(document.getElementById('TBPesquisa').value));">Pesquisar</button>
<script>
function runScript(e) {
if (e.keyCode == 13) {
$("#BTPesquisa").click();
}
}
</script>

Probably, the reason is that the TBPesquia field wasn't found, as this is an asp.net textbox control, and the ID might not be what you expect it to be.
Now you could either go for setting the ClientID property, like:
<asp:TextBox ID="TBPesquisa" ClientID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="return runScript(event)"></asp:TextBox>
or you could rewrite your handler slightly, by doing the following
<asp:TextBox ID="TBPesquisa" runat="server" placeholder="Pesquise produtos aqui" onkeypress="runScript(event)"></asp:TextBox>
and change the runscript to:
function runScript(e) {
var source = e.target;
if (e.keyCode === 13) {
searchFor( source.value );
e.preventDefault();
}
}
function searchFor( textValue ) {
window.location.assign('/Pesquisa?val=' + encodeURIComponent(textValue));
}
I would btw rather put the code for searching outside of the searchbutton itself, it only makes sense to have this outside of your html element

Related

Custom Validator - Error message does not display on front end

I am trying to use a CustomValidator to validate entering of a string - po box
Basically, I want the users to avoid typing their postal address in address box for which I have written a function with the regular expression. But the problem is that the error message does not appear though it triggers the function. (I know this because I checked this by placing breakpoints in my Javascript function using Chome developer tools.)
Below is my .ascx file code.
<div class="clearfix">
<asp:Label ID="lblAddress" runat="server" Text="Address" AssociatedControlID="txtAddress"
class="formlabel firstfocus"></asp:Label>
<div class="input">
<asp:TextBox ID="txtAddress" runat="server" CssClass="large" MaxLength="80"></asp:TextBox>
<asp:RequiredFieldValidator ID="valAddress" runat="server" ControlToValidate="txtAddress"
CssClass="error-block" Display="Dynamic" ErrorMessage="<p>Address is required</p>"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="valAddressPOBOX" runat="server" EnableClientScript="true" ValidateEmptyText="true" ErrorMessage="<p>Cannot contain a PO Box number</p>" ClientValidationFunction="AddressPOBoxValidation" ControlToValidate="txtAddress" Display="Dynamic" SetFocusOnError="True"></asp:CustomValidator>
</div>
</div>
The RequiredFieldValidator triggers the error message.
Below is the screenshot showing error message triggered from RequiredFieldValidator
With CustomValidator the trigger happens but the error message does not come up. I have checked on other CustomValidators on the same ascx page and made sure this one has properties no different from them, but still, if I am missing on any visibility property, feel free to correct me.
Below are 2 screenshots to show how the effect of CustomValidator takes place.
Before entering po box
After entering po box (Notice how the gap between address and address 2 increases.)
Coming on to the Javascript side, below is the function
function CheckPOBOXAddress(address) {
var poboxPattern = /(p\.?\s?o?\.?\s?b\.?(ox)\.?(\s|[0-9])?|post\soffice)/i;
if (poboxPattern.test(address))
return true;
else
return false;
}
function AddressPOBoxValidation(sender, args) {
var address = args.Value;
if (CheckPOBOXAddress(address)) {
args.IsValid = false;
return;
}
args.IsValid = false;
}
I have found a solution to my problem.After days of trial, error and research this worked for me:
<asp:CustomValidator ID="CustomAddressValidator" runat="server" ClientValidationFunction="CheckAddressValidation" ControlToValidate="txtAddress" CssClass="error-block" Display="Dynamic" SetFocusOnError="True">Cannot contain a PO Box number</asp:CustomValidator>
Also I modified my Javascript into a single function :
function CheckAddressValidation(sender, args) {
var address = args.Value;
var addressPattern = /(p\.?\s?o?\.?\s?b\.?(ox)\.?(\s|[0-9])?|post\soffice)/i;
if (addressPattern.test(address)) {
args.IsValid = false;
return;
}
args.IsValid = true;
}
Lesson - The other part of the CreateProfile.ascx file has Custom Validator in the same format as I posted originally. My superiors feel that Microsoft has done some changes to this probably that is why putting an error message in ErrorMessage tag does not seem to work. Feel free to correct me if I am wrong somewhere. But if you're someone who is stuck in a similar situation, my solution should help.

Trigger jQuery function / event from c# code-behind

I hope I will be able to explain my problem clearly.
Scenario:
Asp.net web page with UpdatePanel. Some properties of controls are changeable via UI trigger and are set in jQuery (for faster response, as this page is expected to accept input data of at least 500 records per day).
Example below, (if written in c# code, the logic is like this: txtIDNumber.Enabled = chkIsReceiptRequired.Checked; rfvIDNumber.Enabled = chkIsReceiptRequired.Checked;):
Markup:
<asp:CheckBox ID="chkReceiptRequired" runat="server" Text="Receipt required" />
<asp:TextBox runat="server" ID="txtIDNumber" Width="150px" style="float: left;" />
<asp:RequiredFieldValidator ID="rfvIDNumber" runat="server" ForeColor="Red"
ErrorMessage="Enter ID No." ControlToValidate="txtIDNumber" ValidationGroup="save" />
Snippet of default jQuery code (upon page load, chkReceiptRequired is unchecked, validator and textbox will only be enabled upon ticking chkReceiptRequired):
<script type="text/javascript">
function pageLoad(){
$('input[id$=_txtIDNumber]').prop('disabled', true);
ValidatorEnable($("[id$='rfvIDNumber']")[0], false);
$('input[id$=_chkReceiptRequired]').change(function () {
$('input[id$=_txtIDNumber]').prop('disabled', !$(this).is(':checked'));
$('input[id$=_txtIDNumber]').val(!$(this).is(':checked') ? '' : $('input[id$=_txtIDNumber]').val());
ValidatorEnable($("[id$='rfvIDNumber']")[0], $(this).is(':checked'));
});
}
</script>
I'm using this same page to load the data here to perform record update. Code snippet of data loading:
var maintableComponent = new MainTableComponent();
var maintableData = maintableComponent.GetMainTableDataById(rowId);
chkReceiptRequired.Checked = maintableData.IsReceiptRequired.Value;
txtIDNumber.Text = maintableData.IDNumber;
//todo: enable txtIDNumber and rfvIDNumber from here
The problem: by right, upon page render for update, because chkReceiptRequired is checked, supposedly txtIDNumber should be enabled. But my problem is, it is not. What can I do to enable the txtIDNumber and rfvIDNumber upon data loading from code-behind?
*I have already tried this link and this but it doesn't seem to work.
Please, please help me. The snippets I posted here are just one of many jQuery validations that I desperately need to address. Thanks in advance.
Feeling incredibly stupid right now. Figured out how to fix it after sleeping it off. :P
I just changed the default jQuery code to this:
var isReceiptRequired = $('input[id$=_chkReceiptRequired]').is(':checked');
$('input[id$=_txtIDNumber]').prop('disabled', !isReceiptRequired);
ValidatorEnable($("[id$='rfvIDNumber']")[0], isReceiptRequired);
I just remembered that the last thing in the page-cycle is rendering it on the page so the jQuery can be manipulated by the values set in the control from code-behind.

Unable to get property 'value' of FileUpload in a UserControl using javascript

I have a UserControl (with FileUpload) included on a Master Page as follows:
Master Page
<uc:uploadFiles ID="UC1" runat="server"/>
uploadFiles.ascx
<script type="text/javascript">
function ValidateUpload() {
var FileUpload_function = document.getElementById('myfile');
if (FileUpload_function.value == '') {
return false;
}
else {
//do stuff }
return true;
}
</script>
<div id="div_FileUpload" class="FileUpload_content" runat="server">
<asp:FileUpload ID="myfile" class="FileUpload" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="myfile" ClientValidationFunction="ValidateUpload" />
</div>
When I run the page I get the following error caused by the CustomValidator:
Unable to get property 'value' of undefined or null reference.
My guess is that the FileUpload value is validated before the entire page is rendered because when I delete the UserControl and move the codes to the MasterPage directly, the CustomValidator works fine.
How can I solve the problem?
You need to use .ClientID in document.getElementById. Becasue when you use that in user control, cotnrol id - myfile might be renamed to something else, like ct00_myfile and in that case if you execute same js code, it will give you null.
You need to use following js code.
var FileUpload_function = document.getElementById('<%=myfile.ClientID %>');

Issues with "&" symbol in javascript

I have a aspx page from which some strings are passed into the Javascript function. I am facing a strange issue if the string contains a & symbol.
Here is the simplified version of the code
if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$('#hdnSomeHiddenField').value = "AD&D";
}
and in the UI, the hidden field value is populated in a cell inside a grid.
Now the problem is, even if user is sending "AD&D" from the UI, the variable stringWhichComesFromUI is becoming "AD&Amp;D" thats why the if block never executes.
I have also tried with
if(stringWhichComesFromUI == "AD&D" || stringWhichComesFromUI == "AD&Amp;D")
{
//populate a hidden field
$('#hdnSomeHiddenField').value = "AD&D";
}
This executes the if block, but the value which is going into the hidden field does not show properly in the UI. Value which is displayed in UI is "AD", the "&D" part is gone! I am not able to figure out why, please help?
There is error in syntax of assigning value in jquery. Use this
<asp:TextBox ID="myinput" runat="server" />
<asp:Button ID="SubmitButton" runat="server" OnClientClick="Showme()" Text="Submit" />
<asp:HiddenField ID="hiddenFieldText" runat="server" />
And your script will be like this:
function Showme(){
var stringWhichComesFromUI= $("#myinput").text();
if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$("#hiddenFieldText").val("AD&D");
}
}

OnClientClick not triggering on first click on button after postback

I have an ASP button. On click of it I am opening a pop-up after doing some validations using JavaScript.
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup()" meta:resourcekey="btnHistory" OnInit="btnHistory_Init"/>
function ShowHistoryPopup() {
var age = $get("<%= txtSomeTextBox.ClientID %>");
var str = "";
if (Validate(age)) {
str = 'ClService.aspx?id=' + 'Null,' + age.value;
window.open(str);
}
else {
return false;
}
}
I have a radio button. Based on selected index I need to enable disable the History button. Radio button has 3 options and on 3rd option page postback happens. I need to keep the button enable on 1 st option only. I have implemented this logic with the help of Java Script and some code on OnPreRender event(for post back case).
Now the problem I am facing is, if I select option 1 or 2 and click History button, OnClientCLick event is triggering. But if I select option 3(postback) and then navigate back to option 1, onClientCLick is NOT triggering for the very first time. But on clicking the History button 2nd time its working fine. Anyone having suggestions or solution for this problem?
If I understand your problem I think what's happening is you are posting back after the History Button click which isn't what you want (as there's no click handler). Using this code works for me:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="True" GroupName="Radio1" />
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup();return false;" meta:resourcekey="btnHistory" />
<script type="text/javascript">
function ShowHistoryPopup() {
alert("Here");
}
</script>
All I've added is the return false; after ShowHistoryPopup();
Also, I've used alert here for the purposes of demo, in reality we should really be using console.log('Show my message');

Categories