coffeescript focus is not setting on my field - coffeescript

I want to make client side validation in my project.
Here the requirement is, if the user submitted blank form or he did not field any one input field, then normal html list should have to generate.
Under that list, the all input fields should have to come who has error.
Not only the input field, but it should be the link of that input field.
Once the links came in that list, then user should be able to click on that link. after clicking on that link, then his focus should have to set on the text field.
Here I could create link properly, but I can’t set the focus.
So here my coffeescript:
$(document).ready ->
# first fetch all input field who have errors.
errorElements = $('.content').find('.help-inline').prev()
ul = $('<ul id="errorlist"></ul>')
errorElements.each (i) ->
span = $(this).next()
labelText = $(this).parent().parent().find('label')
$(' <li> <a href="#' + $(this).attr('id') + '" class="errorlink" >' + labelText.text() + ' ' + '(' + span.text() + ')' + '</a></li>').appendTo(ul)
$('#errorcontainer').html(ul)
$(".errorlink").bind "click", (e) ->
# first I am checking it is binding or not.
alert('hello')
$(this).attr(‘href’).setFocus()
I am using simple_form for my html.
So it is generating html for me like this:
<div class=' content '>
<form accept-charset="
UTF-8
" action="
/levels/basic-computer/topics" class="
simple_form form-horizontal
" enctype="
multipart/form-data
" id="
new_topic " method=" post " novalidate=" novalidate ">
<div style=" margin:0;padding:0;display:inline ">
<div class=' form-inputs'>
<div class=" control-group string required topic_title error ">
<label class=" string required control-label " for=" topic_title ">
<abbr title=" required ">
*
</abbr>
Title
</label>
<div class=" controls ">
<input class=" string required " id=" topic_title " name=" topic[title] " size=" 50 " type=" text " value="" />
<span class=" help-inline ">
can't be blank
</span>
</div>
</div>
What I am wrong here?

I was under the impression that just using .focus() on the jQuery object would be sufficient.
jQuery API Docs: Focus
So in theory as long as this is the correctly selected element you only need to do this:
$(this).focus()
Also I notice that you're bind code is outdented from the $(document).ready block.
Another tip in coffeescript $ -> is shorthand for $(document).ready...
For example
$ ->
# do something after the document is ready

Related

How to use result of .length in selector Cypress

I'm trying to perform an action based on the results of an earlier assertion. I have the following situation, I want to determine the number of versions for a document, this is represented in the follwing html:
<ul data-testhook-id="accordion-body">
<li data-testhook-id="accordion-body-item">
<div>
<div data-testhook-id="version-1">
<div data-testhook-id="avatar">
<div data-id="tooltip">John Doe</div>
</div>
</div>
<span data-testhook-id="content">1. 17-08-2018 at 15:26</span>
</div>
<div data-testhook-id="version-2">
<div data-testhook-id="avatar">
<div data-id="tooltip">John Doe</div>
</div>
</div>
<span data-testhook-id="content">2. 20-08-2018 at 13:05</span>
</div>
<div data-testhook-id="version-3">
<div data-testhook-id="avatar">
<div data-id="tooltip">Jane Doe</div>
</div>
</div>
<span data-testhook-id="content">3. 20-08-2018 at 13:11</span>
</div>
<div data-testhook-id="version-4">
<div data-testhook-id="avatar">
<div data-id="tooltip">No Body</div>
</div>
</div>
<span data-testhook-id="content">4. 21-08-2018 at 13:11</span>
</div>
<svg width="12" height="12" data-testhook-id="icon-active-version"><path d="path-here"></path></svg>
</div>
</div>
</li>
Each element with test id data-testhook-id="version-xxx" is a line containing version information and its these div elements I want to count. for this I have set up the following:
cy.get('[data-testhook-id="accordion-body-item"] > div > div').its('length').as('versions')
Now if I add the following assertion, this passes without any problem
cy.get('#versions').should('equal', 4)
But if I try to use the outcome of the number of div's found as a variable in a console.log I no longer get '4' but [object, Object]. Tried this by:
var size = cy.get('[data-testhook-id="asset-versions"] [data-testhook-id="accordion-body-item"] > div > div').its('length')
console.log('foo ' + size)
Which results in foo [object Object] being printed to the console.
What I want to do is use the number of items in a selector to select an element, like:
cy.get('[data-testhook-id="accordion-body-item"] > div > div:nth-child(' + size + ')').find('svg').should('have.attr', 'data-testhook-id', 'icon-active-version')
But as the var is not a number I get the msg
Error: Syntax error, unrecognized expression: :nth-child
[data-testhook-id="asset-versions"] [data-testhook-id="accordion-body-item"] > div > div:nth-child([object Object])
Is it possible to use the number of elements found as a variable for a next selector?
Try this:
cy.get('[data-testhook-id="accordion-body-item"] > div > div').its('length').then((size) => {
cy.get('[data-testhook-id="accordion-body-item"] > div > div:nth-child(' + size + ')').find('svg').should('have.attr', 'data-testhook-id', 'icon-active-version')
});
You cannot assign or work with the return values of any Cypress command. Commands are enqueued and run asynchronously. What commands really return are Chainable<typeOfValueYouWant>, in another words, it's kind of queue object which resolves with desired value.
Read more here
BTW: I think you should consider change your approach for selecting elements. Read more here.
For those who are using Typescript - I wrote plugin for tslint which prevents making this mistake: https://github.com/krzysztof-grzybek/tslint-plugin-cypress

Laravel 5 Forms - Multiple File Upload inside form

I am pretty new when it comes to Laravel and have stumbled across a problem with file uploads inside a form:
Basically I need to upload multiple files when the form is submitted - the initial file upload elements are added dynamically as needed using JQuery as follows:
// Add upload fields to appointment form
var upload_button = $('.upload-appointment-file'); // Upload Button ID
var upload_wrapper = $('.upload-file-holder'); // Field Wrapper
$(upload_button).click(function(e){
e.preventDefault();
$(upload_wrapper).append(
'<div>' +
'<div class="row">' +
'<div class="form-group col-xs-12 col-sm-3 form-group-sm">' +
'<input type="file" name="file_name[]">' +
'</div>' +
'<div class="form-group col-xs-12 col-sm-3 form-group-sm">' +
'<input type="text" class="form-control" name="additional_name[]" placeholder="Document Title">' +
'</div>' +
'<div class="form-group col-xs-12 col-sm-3 form-group-sm">' +
'<select name="priority[]" class="form-control">' +
'<option value="">File Priority...</option>' +
'<option value="1">Important: Signature and Date Required</option>' +
'</select>' +
'</div>' +
'</div>' +
'<div class="row">' +
'<div class="form-group col-xs-12 col-sm-9">' +
'<textarea name="upload_description[]" class="form-control" rows="4" placeholder="Additional instructions for Agent in relation to this file"></textarea>' +
'</div>' +
'</div>' +
'<button type="button" class="btn btn-info remove_upload">Remove</button><hr>' +
'</div>'
);
});
$(upload_wrapper).on("click",".remove_upload", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').slideUp(function(){$(this).remove()});
});
There are other static elements in this form using blade template. When the form is submitted I use a request class to validate the input (class CreateAppointmentRequest extends Request {}) which holds the validation rules in the rules method.
When the validation fails it returns to the original form page - here, I need to reconstruct the file upload input and repopulate the fields with the original data via a #for loop and injecting {{ old('additional_name')[$i] }} etc into the newly created fields (identical to the JQuery created fields).
My problem is that I can obtain all the fields except the original file_name field from the return data. file_name returns an empty array.
When I successfully submit the form file_name is constructed as follows:
"file_name" => array:1 [
0 => UploadedFile {#27
-test: false
-originalName: "pluto_planet.jpeg"
-mimeType: "image/jpeg"
-size: 53963
-error: 0
}
]
All I need to do is somehow get the file name back from the validation error and repopulate the form. I am not sure if I am going about this in the correct way.

Add key eventlistener to last generated input field and stop it after typing

When I click a Button, a form of an unspecific number of input fields will be generated in my dom plus an empty input Field.
I want to add something like a keypress event to the last generated empty input field.
When I start typing, into the last empty input field, another input field should append. This new appended input field should get the keypress eventlistener and the input field I am in should loose the keypress eventlistener.
Here's how I did it(EDIT: added as code snippet):
$(document.body).on("input", ".service-input:last", function (e) {
var lastInput = $(".elementCtr.input-ctr input").last(),
inputID = (parseInt(lastInput.attr('name')) + 1);
$("#providerServicesForm .inputs").append('<div class="elementCtr input-ctr"><input id="service_' + inputID + '" type="text" value="" name="' + inputID + '"></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form accept-charset="UTF-8" name="providerServicesForm" id="providerServicesForm" method="post">
<div class="inputs">
<div class="elementCtr input-ctr"><input type="text" name="1" value="test1" id="service_1" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="2" value="test2" id="service_2" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="3" value="test3" id="service_3" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="3" value="" id="service_3" class="service-input"></div
</div>
</form>
This works fine so far.
But of course I want that this happens only with the first keypress.
After pressing a key, it should stop adding textfields. But when I type something in to the new added (last) textfield it should add a textfield again. But only 1 Textfield after pressing a key etc...
I can't stop the eventlistener after typing.
Does Keypress work with mobile devices?
The great thing about this sort of handler, is if you update the DOM with a new last element, the handler immediately switches to the new element - no need to use .off or .one.
$(document.body).on("input", ".service-input:last", function () {
var inputID = (parseInt($(this).attr('name')) + 1);
$("#providerServicesForm .inputs").append('<div class="elementCtr input-ctr"><input id="service_' + inputID + '" class="service-input" type="text" value="" name="' + inputID + '"></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form accept-charset="UTF-8" name="providerServicesForm" id="providerServicesForm" method="post">
<div class="inputs">
<div class="elementCtr">
<input id="service_0" type="text" class="service-input" value="" name="0">
</div>
<div class="elementCtr">
<input id="service_1" type="text" class="service-input" value="" name="1">
</div>
<div class="elementCtr">
<input id="service_2" type="text" class="service-input" value="" name="2">
</div>
</div>
</form>
One possible enhancement is to detect an empty string and remove the newly added input.
If you only want it to happen for once, why not create a counter and set it to 0. After it had happened, you can increase the counter to 1.
var counter=0;
$(document.body).on("keypress", $(".elementCtr.input-ctr input").last(), function () {
if(counter==0){
//put your logic here
counter++;
}
})

Selecting a DOM Element when (auto-generated) HTML is not well formed

I'm trying to select a control in order to manipulate it but I'm having a problem: I can't select it. Maybe it's because the xml structure, but I really can't change it because it is externally created. SO I have this:
<span class="xforms-value xforms-control xforms-input xforms-appearance xforms-optional xforms-enabled xforms-readonly xforms-valid " id="pName">
<span class="focus"> </span>
<label class="xforms-label" id="xsltforms-mainform-label-2_2_4_3_">Name:</label>
<span class="value">
<input readonly="" class="xforms-value" type="text">
</span>
<span class="xforms-required-icon">*</span>
<span class="xforms-alert">
<span class="xforms-alert-icon"> </span>
</span>
</span>
And what I need is to get the input (line 5). I tryed a lot, for example:
var elem01 = document.getElementById("pName");
console.log("getElementById: " + elem01);
var elem02 = document.evaluate(".//*[#id='pName']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null );
console.log("evaluate: " + elem02);
console.log(elem02.singleNodeValue);
var elem03 = document.querySelector("#pName");
console.log("querySelector: " + elem03);
But none of that allows me to get a reference to the control. What's wrong?
With XPath, the problem seems to be the XML is no well formed, so document.getElementById("pName") doesnt return anything.
http://jsfiddle.net/wmzyqqja/7/
The problem with your example is that you are executing your Javascript before the relevant DOM elements are loaded (i.e. your code is in the head element):
This will fix the example:
window.onload = changeControlValue;
JSFiddle: http://jsfiddle.net/TrueBlueAussie/wmzyqqja/8/
Try this
var elem01 = document.getElementById("pName");
var inp = elem01.getElementsByTagName("input")[0];
(in JSFiddle the "onload" setting is required.)

Could not find installable ISAM

I want to create a search function in my webpage with first
<form id="form1" name="form1" method="get" action="mySearchResults.asp">
<label>Enter Keywords:`
<input type="text" name="searchTerm" />`
</label>`
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
Then
<%
'open the connection
Dim Connect, myRecordSet
Set Connect = Server.CreateObject("ADODB.Connection")
Connect.Open = "Provider=Microsoft.Jet.OLEDB.4.0;Database='SVCS.mdb'"
%>
<%
'collect the form input
searchInput = Request.QueryString("searchTerm")`
'check for a match
Set myRecordSet = Connect.Execute ("SELECT * FROM Inventory WHERE myColumn LIKE '%" & searchInput & "%'")
'display the results
if myRecordSet.EOF then
response.write("You searched for: " & searchInput & "<br>")
response.write("A match was not found.<br>Sorry try again.")
else
response.write("You searched for: " & searchInput & "<br>")
response.write("The record was found!<br>The match is: " & myRecordSet("myColumn"))
end if
%>
<br><br>
Try Again
And the error is
Microsoft JET Database Engine error '80004005'
Could not find installable ISAM.
/sarah lee video club website/mySearchResults.asp, line 5
Please tell me how to solve this
You should not quote the database name for one thing, it is Data Source, not Database, and you do not need the equals with Open.
Set con = Server.CreateObject("ADODB.Connection")
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=SVCS.mdb"
See also http://connectionstrings.com