I am a novice at JavaScript an jQuery. I am writing a project and trying to incorporate $(this) to read a data attribute. Once the data attribute is determined and assigned to a variable, I intend to use that to access other form elements.
Instead of reading the data attribute as intended, clicking the button is submitting the form.
This is a code sample:
<fieldset class="new_inputs" id="new_inputs1">
<label for="file_input_1">Input File:1</label>
<input class="fileRenamingFormInput" name="file_input_1" id="file_input_1" type="text" value="">
<br>
<select class="fileRenamingFormSelect" name="destinationFile_1 id="destinationfile_1">...</select>
<input class="fileRenamingFormFileOut" name="file_out_1" id="file_out_1" type="text" value="">
<br>
<textarea class="copyCommandBlock" name="copyCommandBlock1" id="copyCommandBlock1"></textarea>
<button type="submit" class="btnGenerate" id="btnGenerate1" data-idx="1">Generate command</button> <- Button Javascript might act on
<button type="submit" class="btnCopy" id="btnCopy1" data-idx="1">Copy</button>
</fieldset>
<fieldset class="new_inputs" id="new_inputs2">
<label for="file_input_2">Input File:2</label>
<input class="fileRenamingFormInput" name="file_input_2" id="file_input_2" type="text" value="">
<br>
<select class="fileRenamingFormSelect" name="destinationFile_2 id="destinationfile_2">...</select>
<input class="fileRenamingFormFileOut" name="file_out_2" id="file_out_2" type="text" value="">
<br>
<textarea class="copyCommandBlock" name="copyCommandBlock2" id="copyCommandBlock2"></textarea>
<button type="submit" class="btnGenerate" id="btnGenerate2" data-idx="2">Generate command</button> <- Button Javascript might act on
<button type="submit" class="btnCopy" id="btnCopy2" data-idx="2">Copy</button>
</fieldset>
This is the JavaScript
$("button.btnGenerate").click(function(e){
e.preventDefault();
var idx = $(this).data("idx");
console.log(idx);
});
The logic I am seeking to employ is:
- When "button.btnGenerate" is clicked, don't submit the form
- assign data-idx to variable idx
-
once I have variable idx, I can more efficiently use it plus text strings to get form values from sibling or other form elements. For example, if var idx = 2;
var fnIn = document.getElementById(fileinput'+'idx').value
var fnOut = document.getElementById(fileout'+'idx').value
var str = 'cp '+fnIn+' '+fnOut;
document.getElementById('copyCommandBlock'+idx).value = str;
With the page loaded in the browser there could be multiple fieldsets. They are created dynamically based on the user clicking a button to add another set of fields. I am using $("button.btnGenerate") as the listening event for it is generic.
Is that selector still too generic since it is a class?
Thanks for taking the time to read this. Hope someone can help